Control from Android via wifi. Controlling the machine via WiFi using ESP8266 NodeMCU
This article presents step-by-step instruction, which will help you create your own application for an Android smartphone designed to control something via Bluetooth. To demonstrate, we will analyze in detail an example of blinking an LED on Arduino using commands from a phone or tablet. As a result of following our instructions, you will learn to do this:
To control a home robot, you just need to add buttons and process their commands on the Arduino side.
What will it take?
- Any Arduino-compatible board
- Bluetooth module
- Device on which Android OS is installed
It is best to use HC-05 as a Bluetooth module. It is easy to buy in a Chinese online store or on eBay. The module is powered by 3.3V, but its I/O lines can handle 5V logic, allowing its UART to be connected to an Arduino.
Bluetooth module HC-05
Connecting a Bluetooth module to Arduino
So now we need to connect our Arduino with Bluetooth. If the Arduino does not have a 3.3V output, but only 5V, then you will need to install a stabilizer to reduce the power. The assignment of the HC-05 pins is easy to find on the Internet. For use, we recommend that you make a board with power lines, Rx and Tx. Connection to Arduino must be done in the following order:
- Arduino output 3.3V or (5V through a stabilizer!) - to pin 12 of the Bluetooth module
- Arduino GND output - to pin 13 of the Bluetooth module
- Arduino TX output - to pin 2 of the RX Bluetooth module
- Arduino RX output - to pin 1 of the TX Bluetooth module
After connecting, you need to check the functionality of the Bluetooth module. Connect the LED to pin 12 of the Arduino and upload the following sketch to the board:
Char incomingByte; // incoming data int LED = 12; // LED is connected to pin 12 void setup() ( Serial.begin(9600); // initializing the port pinMode(LED, OUTPUT); // Set pin 12 as output Serial.println("Press 1 to LED ON or 0 to LED OFF..."); ) void loop() ( if (Serial.available() > 0) ( //if data arrived incomingByte = Serial.read(); // read the byte if(incomingByte == "0" ) ( digitalWrite(LED, LOW); // if 1, then turn off the LED Serial.println("LED OFF. Press 1 to LED ON!"); // and print back the message ) if(incomingByte == "1") ( digitalWrite(LED, HIGH); // if 0, then turn on LED Serial.println("LED ON. Press 0 to LED OFF!"); ) ) )
AND HTC Desire with firmware cyanogen 7.1.0 RC1 (Android 2.3.4). Just in case, let me remind you that everything that will be described below only works starting from Android 2.3.4 for phones and Android 3.1 for tablets.
It is worth noting here that this USB Host Shield not entirely successful, especially in combination with Arduino Mega 2560. The first problem was that this fee The extension was made for Arduino UNO, but it differs from Mega in the positions of the SPI contacts, so I had to add jumpers (see photo). The second problem, although quite expected, was the need for external source power supply for the operation of this expansion card. USB Host Shield 2.0 from Circuits@Home is considered more successful, but it is also more expensive.
Board with interconnected SPI contacts
Setting up Arduino software
1. If not already installed, then download and install software for Arduino.2. Download and unpack the ADK package (contains the DemoKit application). The app, firmware, and hardware folders should appear.
3. Download the CapSense library
4. Copy firmware/arduino_libs/AndroidAccessory and firmware/arduino_libs/USB_Host_Shield to
5. Create a CapSense directory in
Firmware download
Google kindly provides its DemoKit sketch for Arduino. All you need to do is open it from firmware/demokit/demokit.pde, compile it and upload it to the board.Test Android application
The DemoKit package also contains the sources of the Android application to demonstrate the capabilities. Google invites us to create an Android project ourselves and assemble this application. First, we will need to install API Level 10. Then everything is simple - we create an Android project and specify the path to the app folder, in the Build Target we specify Google APIs (Platform 2.3.3 , API Level 10). We assemble the application and install it on the phone. Those who don’t want to bother with the assembly can download the ready-made APK.Launch
We simply connect our phone to the USB Host Shield. If we did everything correctly, a request to launch the DemoKit application will appear on the screen.The application itself contains two tabs - In (buttons, joystick and sensors) and Out (LEDs, relays and servos).
I decided that a couple of LEDs and a button were enough for the demonstration. You can see how this whole miracle works in the video.
Some code
In this example, messages transmitted via USB consist of three bytes:The 1st byte defines a command or device group, for example LEDs - 0x2
2nd byte indicates specific device, for example green LED - 0x1
The 3rd byte contains the value transmitted to the device, for example maximum brightness - 0xff
Arduino
... /* initialization */ AndroidAccessory acc("Google, Inc.", "DemoKit", "DemoKit Arduino Board", "1.0", "http://www.android.com", "0000000012345678"); void setup() ( .... acc.powerOn(); ) void loop() ( byte msg; /* check connection */ if (acc.isConnected()) ( /* receive message from Android device */ int len = acc.read(msg, sizeof(msg), 1); if (len > 0) ( /* message for LEDs */ if (msg == 0x2) ( if (msg == 0x0) analogWrite(LED3_RED, msg) ; else if (msg == 0x1) analogWrite(LED3_GREEN, msg); else if (msg == 0x2) analogWrite(LED3_BLUE, msg); ) ) msg = 0x1; b = digitalRead(BUTTON1); if (b != b1 ) ( msg = 0; msg = b ? 1: 0; /* send button state */ acc.write(msg, 3); b1 = b; ) ) )Android
import com.android.future.usb.UsbAccessory; import com.android.future.usb.UsbManager; ... public class DemoKitActivity extends Activity implements Runnable ( private UsbManager mUsbManager; UsbAccessory mAccessory; FileInputStream mInputStream; FileOutputStream mOutputStream; ... private void openAccessory(UsbAccessory accessory) ( mFileDescriptor = mUsbManager.openAccessory(accessory); if (mFileDescriptor != null ) ( mAccessory = accessory; FileDescriptor fd = mFileDescriptor.getFileDescriptor(); mInputStream = new FileInputStream(fd); mOutputStream = new FileOutputStream(fd); Thread thread= new Thread(null, this, "AccessoryThread"); thread.start(); ) ) public void run() ( int ret = 0; byte buffer = new byte; int i; while (ret >= 0) ( // receiving incoming messages ret = mInputStream.read(buffer); i = 0; while ( i< ret) { int len = ret - i; switch (buffer[i]) { case 0x1: // сообщение от кнопки if (len >= 3) ( Message m = Message.obtain(mHandler, MESSAGE_SWITCH); m.obj = new SwitchMsg(buffer, buffer); mHandler.sendMessage(m); ) i += 3; break; ) ) ) ) // example of use - turn on the red LED at full brightness: // mActivity.sendCommand((byte)2, (byte)0, (byte)255) public void sendCommand(byte command, byte target, int value) ( byte buffer = new byte; if (value > 255) value = 255; buffer = command; buffer = target; buffer = (byte) value; if (mOutputStream != null && buffer != -1) ( try ( mOutputStream. write(buffer); ) catch (IOException e) ( ... ) ) ) )conclusions
Opening such Google features first of all, of course, he hopes for the appearance large number active Android accessories, but far from last place is occupied by the fact that in essence we get a convenient device for interacting with various sensors, sensors and actuators. Such a device could easily become the brain of something robotic.Also, we must not forget that Android device for Arduino can act as an expansion board that has GPS, Bluetooth, WiFi, accelerometer and much more.
Would you like to send text message from your Android smartphone to your Arduino board? This article tells you how to do it!
What you need
- Android smartphone with support USB mode host (i.e. OTG support) - most devices running Android 3.1 and higher support this mode. Check your phone with via USB Host Diagnostics App from Play Store;
- Arduino- any version. I will use Uno R3 ;
- USB cable for Arduino;
- USB OTG cable- you need it to connect the Arduino USB cable to the micro-USB port of the phone;
- Android Studio - you need to install it. It's quite easy to do. Android Studio makes application development easier with its assumptions and code generation. This is one of best IDEs. You can also use this article as a guide to Android installation IDE.
Basic components of an Android application
IN Android application there are three main files:
MainActivity.java This is where the executable Java code is located that controls how the application will function. activity_main.xml Contains the application layout, that is, components: buttons, text display components, etc. AndroidManifest.xml Here you define when the application should run, what permissions it needs, and to what hardware he needs to gain access.
There are many more files, but they are all connected to each other using these three.
An activity can be characterized as a screen where the user interacts with the phone. Activities contain widgets such as buttons, text fields, images, etc. that help in conveying information. This tutorial will only use one activity, MainActivity, which will accept user input to send to the Arduino and also display the received text.
Layout
We will use the same layout as the USB App and Bluetooth App. It is simple and contains the minimum widgets needed to test the connection between devices.
As you can see, it contains an EditText widget to receive data from the user, buttons to start the connection, transfer data, end the connection, and clear the TextView . The received data is displayed in a TextView ( empty space under the buttons).
Here is part of the XML code. Because the code for the buttons is similar, it is not shown here. The full code can be downloaded from the link at the end of the article.
I've used a RelativeLayout here, which means that each widget is positioned relative to the widgets around it. The layout can be easily recreated in the Design Tab, where you can drag and drop widgets wherever you want. We need to describe what will happen when the button is pressed. The onClick method is used for this. Specify the method name in the XML code for the button. To do this, add the line:
Android:onClick="onClickMethod"
Now hover your mouse over this line and a warning similar to this should appear on the left:
Click on the “Create onClick...” option. This will automatically add the onClick method code to MainActivity.java. You need to do this for each button.
USB Serial Library
Settings serial connection in Android is quite labor-intensive, as it requires you manual settings a lot of things, so I found several libraries that do it all automatically. I tested several of them and finally settled on the UsbSerial library from Github user felHR85. Among similar libraries that I found, it is the only one that is still updated. It's quite easy to set up and use. To add the library to your project, download latest version JAR file on Github. Place it in the libs subdirectory of your project directory. Then in file explorer in Android Studio click right click mouse on the JAR file and select “Add as Library”. That's all!
Program execution algorithm
This is a short outline of how we will proceed. Every activity has an onCreate() method, which runs when the activity is created. Whatever code you want to run at the beginning must be placed inside this method. Please note that reading from the device is asynchronous, meaning it will work in background. This is to ensure that the data is received as quickly as possible.
Opening a connection
First, let's define an onClick method for the Begin button. When clicked, you need to search for all connected devices and then check if the VendorID of the connected device (vendor ID) is the same as the VendorID of the Arduino. If a match is found, the user must be asked for permission. Each slave USB device has a Vendor ID and a Product ID, which can be used to determine which drivers should be used for this device. Vendor ID for any Arduino board is 0x2341 or 9025.
Public void onClickStart(View view) ( HashMap usbDevices = usbManager.getDeviceList(); if (!usbDevices.isEmpty()) ( boolean keep = true; for (Map.Entry entry: usbDevices.entrySet()) ( device = entry. getValue(); int deviceVID = device.getVendorId(); if (deviceVID == 0x2341) //Arduino Vendor ID ( PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0); usbManager.requestPermission( device, pi); keep = false; ) else ( connection = null; device = null; ) if (!keep) break; ) ) )
Now let's define a BroadcastReceiver to receive broadcast messages to ask the user for permissions and also to automatic start connection when the device is connected, and closing the connection when it is disconnected.
// Broadcast message receiver to automatically start and close a serial connection. private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() ( @Override public void onReceive(Context context, Intent intent) ( if (intent.getAction().equals(ACTION_USB_PERMISSION)) ( boolean granted = intent.getExtras().getBoolean(UsbManager. EXTRA_PERMISSION_GRANTED); if (granted) ( connection = usbManager.openDevice(device); serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection); if (serialPort != null) ( if (serialPort.open()) ( //Set serial parameters connections. setUiEnabled(true); //Enable buttons in the UI. serialPort.setBaudRate(9600); serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8); serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1); serialPort.setParity(UsbSerialInterface.PARITY_NONE); serialPort. setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF); serialPort.read(mCallback); // tvAppend(textView,"Serial Connection Opened!\n"); ) else ( Log.d("SERIAL", "PORT NOT OPEN"); ) ) else ( Log.d("SERIAL", "PORT IS NULL"); ) ) else ( Log.d("SERIAL", "PERM NOT GRANTED"); ) ) else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) ( onClickStart(startButton); ) else if (intent.getAction ().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) ( onClickStop(stopButton); ) ); );
If the first IF condition is met, and if the user has given permission, then start connecting to the device whose Vendor ID matches the Vendor ID we need. Moreover, if accepted broadcast message about connecting or disconnecting a device, manually call the onClick methods for the Start and Stop buttons. SerialPort is defined using device and connection as arguments. If successful, open SerialPort and set the appropriate parameters. The parameter values for Arduino Uno are: 8 data bits, 1 stop bit, no parity bit, flow control disabled. The baud rate can be 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600 or 115200 bps, but we will use the standard 9600 bps.
Receiving data from the device
In the code snippet above, notice the line containing serialPort.read(mCallback) . Here, the read function is passed a reference to a Callback object, which will automatically fire when incoming data is detected.
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() ( // Define a callback method that is called when data is received. @Override public void onReceivedData(byte arg0) ( String data = null; try ( data = new String(arg0, " UTF-8"); data.concat("/n"); tvAppend(textView, data); ) catch (UnsupportedEncodingException e) ( e.printStackTrace(); ) ) );
The received data will be in the form of raw bytes. We'll have to recode them to readable format eg UTF-8. They are then added to the TextView using special method tvAppend() . This is done this way because any changes to the user interface can only be done on the thread user interface. Since this Callback will be run as a background thread, it cannot directly affect the user interface.
Private void tvAppend(TextView tv, CharSequence text) ( final TextView ftv = tv; final CharSequence ftext = text; runOnUiThread(new Runnable() ( @Override public void run() ( ftv.append(ftext); ) )); )
Transferring data to the device
Transferring data is relatively simple compared to reading data from a device. This is a simple function call with the bytes of data to be passed as an argument. This will be implemented in the method onClick buttons Send.
SerialPort.write(string.getBytes());
Closing a connection
To close the connection, simply close the serial port.
SerialPort.close();
Application manifest
The manifest declares what additional permissions the application may require. The only permission we need is permission to do phone usb host. Add next line to the manifest:
The application can be forced to start automatically by adding an intent filter to main activity MainActivity. This intent filter will be triggered when any new device is connected. The device type can be specified explicitly using the Vendor ID and/or Product ID in the XML file.
Note the line " android:resource="@xml/device_filter ". This tells the compiler that it can find the device properties in a file called device_filter in the src/main/res/xml directory, so create a subdirectory " xml " in the src directory /main/res and place a file with the following content in it:
Application testing
Build the application and run it on your smartphone. Now launch the Arduino IDE and configure the Arduino to simply echo whatever the board will accept via the serial port. Here's some very simple code to help you do this:
Void setup() ( Serial.begin(9600); ) void loop() ( char c; if(Serial.available()) ( c = Serial.read(); Serial.print(c); ) )
Now connect the Arduino to the microUSB port of your phone using an OTG cable. The application should launch automatically. Try sending some text and the same data will be returned!
Conclusion
This article shows how Arduino can communicate with your smartphone. And the possibilities for using it are endless! In the case when data is needed from any sensor that is not among those built into the smartphone, you can use any microcontroller to read data from this sensor and transfer it to the smartphone. The next article will show you how to connect your smartphone to Arduino using the popular HC05 bluetooth module.
Machine on arduino and Bluetooth without code editing. We will use specialized free software to create the sketch. In addition, you don’t need to buy a chassis for our craft; almost any faulty radio-controlled model of a car or tank will do.
I suggest watching an overview video about the Bluetooth-controlled machine and its contents.
So, let's look at a live example of how to make a machine with your own hands, remotely controlled via bluetooth from an Android tablet or smartphone. The article, oddly enough, is intended for an initial level of knowledge. There is no guide to editing code in the Arduino IDE, and we will only use it to fill in our code. And we will compose the control algorithm in a program called FLProg. Control program from a smartphone - HmiKaskada_free. But first, about the hardware we need.
Machine on arduino and Bluetooth - hardware.
The first thing you need is chassis, that is, a body with wheels and motors, which will drive for the joy of us and those around us. In my case, I used a case from a radio-controlled toy in which the power part burned out. The prospect of renovation seemed dull to me, and I wanted something new for my children. That's how this project was born. The body contains two engines that drive the wheels on the sides of the machine, like a tank. All electronic components were sent for spare parts.
To control the electric motors of our future creation we will need H-bridge on L298N chip Link to Ali, I took this one from. The picture is clickable.
H-bridge for arduino
Can control two motors in the voltage range 5 - 35 volts. Supports PWM, that is, you can adjust the engine speed. The board has a stabilized voltage output of 5 volts for powering the Arduino.
The connection diagram is simple and unpretentious:
The next integral part of the electronic filling of our project is bluetooth module HC-06. The most common module for Arduino, so popular that in additional description does not need.
HC-06 bluetooth for arduino
The main element and brain in my case is arduino nano, I won’t even post photos here because everyone knows about it and knows how to work with it. By the way, any Arduino board will do, as long as it fits in the case 😀
Batteries and soldering wires do not require specification. The choice of batteries depends on the operating voltage of the electric motors.
Machine on arduino and Bluetooth - drawing up a sketch.
I repeat - there will be no digging in the code here. We will use popular program FLProg. You can download its latest version on the official website. The program's interface is simple and unpretentious, but it has enormous functionality and support for almost all popular modules. I won’t write how to use it because it would take a couple of articles. Let me just say that I have never met a more convenient and available program for making sketches for arduino and its clones. Interface screen:
FLProg interface
The site is full of text and video manuals, I think you’ll figure it out.
My project for a remote-controlled car can be downloaded from Yandex disk via the link shortening service.
Machine on arduino and Bluetooth - control interface on an Android tablet.
By popular demand I wrote detailed instructions on developing a control interface based on HmiKaskada android in the article. The link is clickable.
For devices under android control there is a program HmiKaskada (link to YandexDisk). It was originally developed as an alternative to expensive industrial HMI panels. But inquisitive minds quickly realized that she could control anything. In our case, a typewriter. Supports wireless interfaces Wi-Fi and Bluetooth, in addition, you can connect the device directly via USB.
There are paid and free versions of the program. I have both but I basically made the project in free version to show you and once again make sure it’s absolutely working free versions. The main difference between free and PRO versions This works only via bluetooth.
There is a giant thread on the FLProg forum regarding compatibility with KaScada, and the developer is active and sociable. I don’t see any point in posting a screenshot of the control panel - it’s in the video.