- Creating Bluetooth Android App to Control Arduino Board
- Development environment
- How this app works
- Creating Bluetooth Connection on Android
- Creating Activities and Java Class
- AndroidManifest.xml
- MainActivity Layout
- SelectDeviceActivity Layout
- MainActivity Code
- SelectDeviceActivity, DeviceListAdapter and DeviceInfoModel
- Modifying the Arduino Code
- Connecting Android to Arduino…
- …And Test the Data Exchange
- What’s next
- BLUETOOTH CONTROL LEDs © Apache-2.0
- Simple Bluetooth Lamp Controller Using Android and Arduino
Creating Bluetooth Android App to Control Arduino Board
This tutorial is about creating your custom Android app to connect with an Arduino board using Bluetooth. Consequently, some basic prior knowledge of Android programming is required to follow this tutorial.
But don’t worry, if you don’t have basic knowledge on Android programming but still want to create your own Bluetooth app, then you can take the Basic Android Programming for Arduino Makers that is available in Udemy. You will learn how to create a Bluetooth app that can talk with your Arduino board from scratch and without prior knowledge in Android programming required.
The codes presented in this tutorial is the minimum codes that enable an Android phone and Arduino board to send and receive messages (that can be translated into commands) with each other through Bluetooth.
Development environment
To manage some expectations in case the app doesn’t work like it’s supposed to be, this is the environment I use to develop this app:
- Samsung Galaxy S8, with Android version 9.
- Android Studio version 3.6.3 with compatible Gradle version.
- Minimum SDK Version: 19 (You need to select this when creating a new project using Android Studio).
- Mac OS 10.15.4 (Windows machines also works perfectly)
How this app works
This app will create a Bluetooth connection with a nearby Arduino board that has been connected with the HC05 Bluetooth module. It is created to be compatible with Arduino board from this tutorial. However, it is easy to modify the codes so that it can be used together with Arduino boards with different configurations.
To test Bluetooth connection functionality, you can press the button on this App to control a built-in LED on the Arduino board. Once a predefined command message is received from Android, Arduino will transmit a return message to Android as a status message.
Creating Bluetooth Connection on Android
Before we dive into the coding part, I would like to describe the step by step flow to create a Bluetooth connection on Android. This is a summary of the more detailed documentation from Google.
- Initialize the default Bluetooth adapter (device) on your Android phone.
- Get the MAC Address from the remote device that you are connecting to. In this case, the MAC Address of HC05 Bluetooth module connected to Arduino board.
- Create a separate thread in your code to initiate a connection using the MAC Address that we previously obtained. This thread will manage what happens if a connection is successfully established or failed to be established. It also handles if we want to close the Bluetooth connection.
- Once a connection is successfully established, the thread will do callback for the codes that manage data exchange (transmit and receive between 2 devices). For this, we need to create another thread.
- This thread will read incoming data transmission and parse it if necessary (or you can parse it elsewhere on the code) and transmit the message or command that is generated by the Android app.
Now, the flow above needs to be translated into codes.
Creating Activities and Java Class
Create a new project with the empty activity template and select the appropriate name for your app. For this app we will create 2 activities and 2 Java classes :
- MainActivity. This is automatically created when you create a new project. This is where most of the interactions take place.
- SelectDeviceActivity. The UI where you select the Bluetooth device that you want to connect.
- DeviceListAdapter. A class to display a list of paired Bluetooth devices for you to connect. The list will be displayed in SelectDeviceActivity.
- DeviceInfoModel. A class that acts as a placeholder for the remote device information.
AndroidManifest.xml
Once you created all the activities and classes above, your AndroidManifest.xml file will look something like this :
Please note that you should add the Bluetooth permission so that you can access your phone’s Bluetooth device.
MainActivity Layout
MainActivity is the main UI where you can interact with the interfaces that will connect you to a remote Bluetooth device and control it.
The XML code for the layout above is like this:
SelectDeviceActivity Layout
This activity will display a list of remote Bluetooth devices that are already paired with your phone. It is shown when the “Connect” button is clicked on the MainActivity. The layout XML code for this activity is as follows:
MainActivity Code
Now we continue with the code. Code in MainActivity is the one creating a Bluetooth connection to a remote device. You can just copy and paste the code below to your project. Some comments have been added to the code you can understand it better.
I make some minor style changes to the color resources.
SelectDeviceActivity, DeviceListAdapter and DeviceInfoModel
This activity works with DeviceListAdapter class and DeviceInfoModel class to display the list of paired devices.
The whole Android project is also available on Github.
Once you build the whole project, you need to install the app to your actual device to be able to use the Bluetooth function.
Note: Due to periodic update to the app, the Github version might slightly different from the code in this post. But the core function remains the same.
Modifying the Arduino Code
We need to make some small modifications to the Arduino code from this tutorial. You can create a new Arduino sketch and copy-paste the code below.
Don’t forget to compile and upload the code to your Arduino board. You can also go to Github to get this code.
Connecting Android to Arduino…
Follow the steps below to connect your phone to the Arduino board
- Connect HC05 module to the Arduino board as described in the previous post then connect it to a power supply. The LED on HC05 module should be blinking fast.
- Activate Bluetooth on your phone and pair HC05 with your phone. The device name you’re looking for is “HC-05”. You don’t need your app yet for pairing with HC05.
- Now open your app and press the “Connect” button. A list of paired devices will be shown on screen. If you change the device name when you’re pairing with HC05, you actually only change the alias name. Your app only shows the device name, so select “HC-05”.
- Once HC05 is connected, there will be status on the toolbar and the LED button will be enabled. You know when HC05 is connected when the LED on HC05 blinks slowly.
…And Test the Data Exchange
Now, you can press the LED button and watch the built-in LED on Arduino turned on and off. Visually, you can also see the light bulb image on your phone change color to indicate LED status. The color changes when your phone receives the status message from Arduino, so you might notice some delay between the change on LED on Arduino with the light bulb image on your phone.
What’s next
You have now understood one of the methods to connect your Android phone to an Arduino board. Exciting new possibilities are now available for you. For example, you can:
- Improve the app so that it shows alert when Bluetooth function on your phone is not yet activated.
- Add more codes on Arduino so now your app can control 2 LEDs
- Connect a simple sensor on Arduino e.g. proximity sensor and read the values on your phone.
- And many more. If you can imagine it, you can create it.
If you find this tutorial is too difficult to follow or if you don’t have prior knowledge in Android programming, then you can always take the course Basic Android Programming For Arduino Makers in Udemy which will guide you to create your own Bluetooth app from scratch.
Источник
BLUETOOTH CONTROL LEDs © Apache-2.0
This project uses android bluetooth for controlling LED
| × | 1 | ||
| × | 1 |
You already know what we are gonna do today…so lets get started !
Things you’ll need :-
- Arduino board
- Breadboard
- Bluetooth module/sensor – HC05
- Couple of jumpers/single stranded wires
- LEDs
- An ANDROID(obviously 😛 )
Video tutorial down below↓
Connections Of Bluetooth module HC05 :-
VCC – to VCC of Arduino. GND – to GND of Arduino. RX – to digital pin 0(TX pin) of Arduino. TX – to digital pin 1(RX pin) of Arduino. (connect RX & TX pin after uploading the code)
Of LED – Positive terminal – to pin 8 of Arduino. Negative terminal – GND of Arduino.
Download the app called BlueControl (It’s free). Here is the link Open the app Blue control (It will automatically turn on the device’s Bluetooth). Go to options. Click on “Connect to Robot”. Choose the device – HC 05.
- Make the connections as shown in the above image. Don’t connect the RX & TX pins WHILE/BEFORE uploading the code !
- Copy the code given below.
- When you are connecting to the Bluetooth module for the first time, it will ask you the password. Enter 0000 OR 1234.
- When the device gets successfully paired with the sensor, the LED lights on sensor will start blinking at a slower rate than usual.
- DONE. Copy the code given below & test it out !
Code for BLuetooth sensor HC-05:
You may like it –
Control LEDs with Voice command (in 2 mins, just change code)
Here’s a video tutorial which will surely make your job easy… 🙂
Make an Obstacle avoiding robot using Ultrasonic sensor (in 10 mins)
Comment below if you face any difficulties. I’ll solve them for you ASAP
Источник
Simple Bluetooth Lamp Controller Using Android and Arduino
Making a simple system to controll a lamp or some other appliance in your house.
- 54,546 views
- 24 comments
- 29 respects
| × | 1 | ||
| × | 1 | ||
| × | 1 | ||
| × | 1 | ||
| × | 1 | ||
| × | 1 |
The hability to control any appliance around your house using only your smartphone is very interesting. This project consists of using an Arduino, a cheap bluetooth module and a relay to control, for example, a lamp, by connecting it with your smartphone via bluetooth. This project is intended to be simple using the least amount of resources and code, but still including important demonstrations and descriptions of the whole process.
IMPORTANT NOTE: This project involves using high voltage devices, hence, extreme caution is advised and if possible do this project under the supervision of someone experienced.
2. Content Briefing
In the next sections, we’ll discuss some topics in the sequence shown below and in more detail.
- 3. Demo
- 4. Schematic
- 5. Arduino code
- 6. Android code (sources & apk in here (github))
Let’s start by setting up our bluetooth module (bottom left component in the figure). As you can see we pull out both 5V and Ground from our Arduino all the way through to the Bluetooth Module (Red and Black wires). For the communication pins we will need to attach the Transmitter pin (TX) to the Arduino’s receiver pin (RX) (Green Wire) and the Transmitter pin to the Arduino’s Receiver pin (Orange wire). If you check the back of your bluetooth module it will have a label showing how much voltage it’s receiver pin can handle (In my case it’s 3.3V) and since our Arduino supplies 5V, the bluetooth module would probably burn up after frequent uses, that’s why we need to reduce that voltage to 3.3V. Hence, it has been included 2 resistors that work as a «voltage divider» that go through the orange wire. the first R1 resistor is a 560 OHMS while the second one R2 is 1K OHMS. I used these resistors because it was what I had in my equipment but if you have any other resistors maybe you can find the right set for you using this Formula and that brings the voltage down a bit:
Vout = (Vsource x R2)/R1+R2
In my case I got:
Vout = 5 x 1000 / 1560 = 3.2V.. close enough..
(Search for Voltage Divider Calculators on Google and it will give you good explanation and quick calculations).
As for the Relay, we also supply it with both power and ground (Red and Black wires) and a signal wire connected to Arduino’s pin number 10 that will command the relay when to power ON or OFF our lamp, for example.
The blue wires represent the wires of the plug/socket extension. Obviously you will not want to connect the relay directly to a lamp’s built-in plug extension which you would purposly ruin for this project, so what is recommended is to buy a standalone plug/socket extension. What I did was to buy a smaller wire and add to it both plug and socket just as it’s represented in the photo of the slideshow above.
Now that you have your extension, pull out 1 of the wires extension and cut it, you will end up with 2 wire ends (shown in the 2 photos above). But where can you connect these 2 ends to the relay?. The Relay has 3 ports, NC (normally closed), C (Common), NO (normally open). This means that, when the relay is at it’s normal state (no signal sent to the relay) there will be a connection between NC and C ports. When a signal is sent a connection will be set between C and NO instead. So that’s why we connect our 2 wire ends to both C and NO because we want to send a signal to our relay in order to let the current flow through these two channels and provide energy to our appliance. Great explanation here: http://www.pcbheaven.com/wikipages/How_Relays_Work/
The Arduino’s code shown above is generally structured in 4 phases.
- 5.1. Initializations
- 52. Setup
- 5.3. Loop
- 5.4. Process Command
It is important to note that all the code above is in the Arduino’s point of view, meaning that all the ‘reading’ operations are operations where the arduino is receiving data from some other source, and the write operations are operations where the arduino is sending messages to other source as well. The sequence of usage in our system will be like this:
- a. The user clicks a button in the smartphone engaging a bluetooth command.
- b. The bluetooth module receives it and sends that command to the Arduino.
- c. The Arduino will then process that command and send a signal to the relay to turn it ON or OFF.
- d. The Arduino then sends a sucessfull message to the bluetooth module, where the bluetooth module sends this message back to the smartphone.
5.1.Initializations
In the first few lines of code, we start by including the SoftwareSerial library that will allow us to communicate with the Bluetooth module. It also lets us use different pins as a receiver and transmitter pins than the ones predefined for Arduino (pin 0 = RX and pin 1 = TX). Instead we’ll use pin number 2 for Arduino’s RX and pin 3 for Arduino’s TX. Then we create constants that identifies the pins we wish to use for each of our components, in this case, the Arduino’s pin that will controll the RELAY is number 10 and the pin to controll the built-in LIGHT on Arduino’s is number 13.(this is optional, if you don’t want to use it it’s fine). Then, the data structure called ‘data’ of type ‘char’ acts as a buffer for our incoming messages from the bluetooth module, and some more auxilliary variables for our data structure ( flag, index, c ) that will be explained in the Loop section.
5.2. Setup
The predefined method ‘setup’, will be the first method to be executed before our actual intended program starts running. It basically allows us to configurate some of the Arduino’s pins and other stuff before the main program executes. Therefore we start by saying that the RELAY pin will be an OUTPUT pin since we want to send a signal to either turn OFF or ON the Relay. The same for the LIGHT pin. Additionally, we can choose if we want to start the program and start sending the signal right away using ‘digitalWrite’. In case of the relay we do want to start sending a signal because the way the Relay works is a bit counter-intuitive because the way the relay works is that when a signal is detected by de relay, then it switches itself OFF, else it switches back ON.
5.3. Loop
The loop is the method that, as the name suggests, is iteratively being called in order to repeatedly process whatever information we pass onto it. With that being said, we start by checking if there are incoming messages from the bluetooth module, and if there are, then we enter a cycle to keep reading those messages byte by byte (reading a type ‘char’ every iteration). About the line of code delay(10), to be honest i’m not completely sure why the code only worked with that delay(10). When I tried without that line of code, the messages weren’t being received properly into the array of chars called ‘data’ (our buffer) and all I got was a bunch of junk in the buffer. My best guess, and it was the reason why I used it, would be the fact that there are different processing speeds in receiving and transmitting of our components, which in this case is the Arduino and Bluetooth Module. In some Arduino code over the web is costume to see some of those delays lines of code and probably some of them are likely to be used for that matter. After this delay, suppose we have read the first byte (char) of our message, we then add it to our buffer and increment the counter called »index» to keep adding more bytes iteratively and incrementally along the dimension of the array/buffer. After the message as been read, we exit the while loop and say «yes», there is a message to be processed (by setting the flag to true). And also add a ‘\0’ to indicate the buffer’s end. Finnaly, at the end of the loop method we simply check if there are messages to process, and if there is we then call the processCommand method for that matter, clearing/reseting our buffer afterwards by setting the first index of the array([0]) to null (‘\0’) and setting the counter (‘index’) to 0. This way our buffer is ready to receive more incoming messages.
5.4. Process Command
Finnally, the processCommand method will be the method that will decide what to do with the bluetooth message received previously in the loop code section. For this project, I decided to send simple commands sent from the smarthphone to the Arduino through bluetooth. To turn the relay ON, a simple message built on the Android application will send the following String as bytes: «RY» (Relay Yes) if we wish to turn the relay ON or «RN» (Relay NO) if we wish to turn the relay off. Like mentioned before, I also included a «add-on» where you can controll the Arduino’s built-in LED ( pin number 13 ) and so the commands are «LY» and «LN» but you don’t have to use it. Remember that to turn ON the Relay we need to send a LOW signal from the Arduino and vise-versa. The Arduino will also send a status message such as for example «Relay: ON» back to the bluetooth module which in its turn will send to the user.
In this section we’ll discuss how the Android app was implemented to communicate with the Bluetooth module. I will not cover some aspects of the Android functionality and how you are supposed to do certain things, but mainly the contents of the source code and explain it a bit better. But in general, the app was created using Android Studio (AS), and AS allows you to choose a simple template to start your application, select that basic template. Then, AS has set up all the things you need to start your app, including the Android Manifest which is where you include the app’s general properties such as what permissions the app is going to need. A simple blank layout where you can add some components like buttons, and one java source code that initializes the app and controls all the UI stuff on the layout. If you haven’t chosen the basic template and chose the empty template instead then you can always create a new activity which sets up a layout and corresponding source file that you’ll need. Also the source code and resources can be found on my github: https://github.com/serge144/ArduinoConnectorBT
So here’s what we’ll cover next:
- Android Manifest
- Simple Layout
- Java Source Code (Ardcon.java + ConnectedThread.java)
6.1 Android Manifest
The android manifest describes the application’s main structure and what OS’s functionalities will the app make use of. In our case we need to include permissions related to the Bluetooth interface. As we can see from the code shown above, the following lines were inserted in order to use the OS’s Bluetooth functionalities:
6.2 Simple Layout
The layout is presented in the following figure:
Источник