Control an Arduino with Bluetooth

Harness the power of Bluetooth to communicate with your Arduino!
This is part two of a series, which will focus on using Bluetooth to communicate with an Arduino. Bluetooth is one of the popular wireless communication technologies because of its low power consumption, low cost and a light stack but compensates on range.

Requirements

  • An Arduino
    Any model of the Arduino can be used, but all code and schematics in this article will be for the Uno.
  • An Android Smartphone with Bluetooth
    Check if your phone has Bluetooth by navigating to "Wireless and Networks" under settings.
  • HC-05 Bluetooth Module
    This module is the most popular Bluetooth module out there. The basic version is pretty inexpensive. The hassle of having to connect wires between the module and the Arduino can be avoided by using a Bluetooth Shield or a version in the Bee shape, the BTBee  and a Bee shield.
  • Android Studio
  • USB cable for the Arduino

Setting Up the Hardware

To use the HC05 module, simply connect the VCC to the 5V output on the Arduino, GND to Ground, RX to TX pin of the Arduino, and vice versa. If you are using the BTBee module with the shield, set the jumpers on the board so that the DOUT pin and D0 pins are shorted and DIN and D1 pins are shorted. This is done because the RX pin on the Arduino is Pin 0 and the TX pin is Pin 1. You are free to use any other pins as the RX and TX Pins, but you will have to use the SoftwareSerial Library of the Arduino to enable that. Do remember to remove the jumpers while uploading code to the Arduino if you have selected Pin 0 and 1 as Serial pins.

Connecting the HC05 Module

Jumper connected to Pins 0 and 1 on the BTBee shield
If the module is being used for the first time, you'll want to change the name, passcode etc. To do this the module should be set to command mode. Connect the Key pin to any pin on the Arduino and set it to high to allow the module to be programmed. If you're using the BTBee, it's a little tricky. While the official wiki says that the Mode Button must be held to change it to Command Mode, and releasing it changes it back to Data Mode, it doesn't happen that way: instead, hold the Mode button, then quickly press and release the Reset button. You will notice that the Status LED blinks slower than usual.
To program the module, a set of commands known as AT commands are used. Here are some of them:
AT Check connection status.
AT+NAME ="ModuleName" Set a name for the device
AT+ADDR Check MAC Address
AT+UART Check Baudrate
AT+UART="9600" Sets Baudrate to 9600
AT+PSWD Check Default Passcode
AT+PSWD="1234" Sets Passcode to 1234
All the set commands return "OK" when they are executed successfully.
Here's some code to change the name. The jumpers are connected to 4 and 5 because the response from the module will be printed on the Serial Monitor. The complete code is available at the end of this article in the "download code" button.

                    //If youre not using a BTBee connect set the pin connected to the KEY pin high
#include 
SoftwareSerial BTSerial(4,5); 
void setup() {
  String setName = String("AT+NAME=MyBTBee\r\n"); //Setting name as 'MyBTBee'
  Serial.begin(9600);
  BTSerial.begin(38400);
  BTSerial.print("AT\r\n"); //Check Status
  delay(500);
  while (BTSerial.available()) {
      Serial.write(BTSerial.read());
    }
  BTSerial.print(setName); //Send Command to change the name
  delay(500);
  while (BTSerial.available()) {
      Serial.write(BTSerial.read());
    }}
void loop() {}
                  

Programming the Arduino

No extra library is used to connect to the Bluetooth module because the RX and TX pins of the Arduino are shorted with those of the module. All data--outgoing and incoming--will have to go through the module. Interfacing the module is that easy.
To see how this works, let us connect a DHT-11 Temperature Sensor to the Arduino. When the letter "t" is received, the temperature, humidity, and heat index will be transmitted back. To use the DHT-11, the DHT library by Adafruit is used.


The Shield and the connected DHT Sensor
Below is the code used to read data from the DHT sensor, process it, and send it via Bluetooth.

                    #include "DHT.h"
#define DHTPIN 2     
#define DHTTYPE DHT11  
DHT dht(DHTPIN, DHTTYPE);
void setup() {
  Serial.begin(9600);
  dht.begin();}

void loop()
{  char c; 
if(Serial.available())  
  {  
   c = Serial.read();  
   if(c=='t')
   readSensor();
  }}
void readSensor() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  float hic = dht.computeHeatIndex(t, h, false);
  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" *C ");
}
                  

The Android App

Take a look at the previous article for a quick intro about Android apps and also the layout for this app.

The program flow will be as illustrated above.

Editing AndroidManifest.xml

Since the extra hardware this app will be using is the onboard Bluetooth adapter, it will have to be mentioned in the Manifest.
uses-permission android:name="android.permission.BLUETOOTH" />

Connecting to the Device

First check for the presence of a Bluetooth Adapter.
        BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();

        if (bluetoothAdapter == null) {

            Toast.makeText(getApplicationContext(),"Device doesnt Support Bluetooth",Toast.LENGTH_SHORT).show();

        }

If it is present, check if it's enabled. If it isn't enabled, ask the user permission to enable it.
if(!bluetoothAdapter.isEnabled())

        {

            Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

            startActivityForResult(enableAdapter, 0);

        }
The device must be paired before the app can use it. Check the section below for details on how to pair the BT Module and the Phone. Now that the adapter is enabled, check for paired/bonded devices. Using the AT Commands from the section above, give an appropriate name to the device. Also find out its MAC Address. Here, the MAC addresses are being compared for a match because names are liable to be changed often.
Set bondedDevices = bluetoothAdapter.getBondedDevices();

if(bondedDevices.isEmpty()) {

     Toast.makeText(getApplicationContext(),"Please Pair the Device first",Toast.LENGTH_SHORT).show();

} else {

     for (BluetoothDevice iterator : bondedDevices) {

          if(iterator.getAddress().equals(DEVICE_ADDRESS)) //Replace with iterator.getName() if comparing Device names.

          {

             device=iterator; //device is an object of type BluetoothDevice            

             found=true;            

             break;

          } } } 
After getting the BluetoothDevice, a socket has to be created to handle the outgoing connection. Here a RFCOMM socket is used. RFCOMM--also known as Serial Port Profile--is essentially a Bluetooth protocol to emulate an RS232 cable. ​
socket = device.createRfcommSocketToServiceRecord(PORT_UUID); socket.connect();
Then get the input and output streams of the socket.
outputStream=socket.getOutputStream();

inputStream=socket.getInputStream();

Reading Incoming Data

Since data can be received at any point of time, running a thread to listen for data would be best. First, the input stream is queried for available data. Then, the bytes are converted to human readable UTF-8 format and the text is send to a handler to post onto the UI. This is done because the UI can't be updated from background threads.
        int byteCount = inputStream.available();
        if(byteCount > 0)
         {
            byte[] rawBytes = new byte[byteCount];
            inputStream.read(rawBytes);
            final String string=new String(rawBytes,"UTF-8");
            handler.post(new Runnable() {
                    public void run()
                    {
                        textView.append(string);
                    }
            });
          }

Transmitting Data

To send data, pass the String to the OutputStream.
outputStream.write(string.getBytes());

Download the Source Code for the App

 

Testing the App

First off, pair the phone and the module by scanning for new devices in the Bluetooth tab of the System Settings. The name which was set earlier should appear. Put in the set passcode (Default is either 0000 or 1234).

After you power on the Arduino, you may notice that the BTBee's status LED blinks periodically. Now open the app and tap Begin. The status LED must go off and the Conn LED will glow. This shows that a connection has been established.

When "t" is sent to the Arduino, it replies with the Temperature, Humidity, and Heat Index.


That was a simple exhibition of data transfer using Bluetooth. Bluetooth can be used to control the automation of many everyday things, like switching a lightbulb on, which can be done by using a Relay with the Arduino. This concludes this two-part series on interfacing an Arduino with an Android phone. The first part on using a Serial Cable can be found here.
Previous
Next Post »
My photo

Hi, I`m Sostenes, Electrical Technician and PLC`S Programmer.
Everyday I`m exploring the world of Electrical to find better solution for Automation. I believe everyday can become a Electrician with the right learning materials.
My goal with BLOG is to help you learn Electrical.
Related Posts Plugin for WordPress, Blogger...

Label

KITAIFA NEWS KIMATAIFA MICHEZO BURUDANI SIASA TECHNICAL ARTICLES f HAPA KAZI TU. LEKULE TV EDITORIALS ARTICLES DC DIGITAL ROBOTICS SEMICONDUCTORS MAKALA GENERATOR GALLERY AC EXPERIMENTS MANUFACTURING-ENGINEERING MAGAZETI REFERENCE IOT FUNDAMENTAL OF ELECTRICITY ELECTRONICS ELECTRICAL ENGINEER MEASUREMENT VIDEO ZANZIBAR YETU TRANSDUCER & SENSOR MITINDO ARDUINO RENEWABLE ENERGY AUTOMOBILE SYNCHRONOUS GENERATOR ELECTRICAL DISTRIBUTION CABLES DIGITAL ELECTRONICS AUTOMOTIVE PROTECTION SOLAR TEARDOWN DIODE AND CIRCUITS BASIC ELECTRICAL ELECTRONICS MOTOR SWITCHES CIRCUIT BREAKERS MICROCONTROLLER CIRCUITS THEORY PANEL BUILDING ELECTRONICS DEVICES MIRACLES SWITCHGEAR ANALOG MOBILE DEVICES CAMERA TECHNOLOGY GENERATION WEARABLES BATTERIES COMMUNICATION FREE CIRCUITS INDUSTRIAL AUTOMATION SPECIAL MACHINES ELECTRICAL SAFETY ENERGY EFFIDIENCY-BUILDING DRONE NUCLEAR ENERGY CONTROL SYSTEM FILTER`S SMATRPHONE BIOGAS POWER TANZIA BELT CONVEYOR MATERIAL HANDLING RELAY ELECTRICAL INSTRUMENTS PLC`S TRANSFORMER AC CIRCUITS CIRCUIT SCHEMATIC SYMBOLS DDISCRETE SEMICONDUCTOR CIRCUITS WIND POWER C.B DEVICES DC CIRCUITS DIODES AND RECTIFIERS FUSE SPECIAL TRANSFORMER THERMAL POWER PLANT cartoon CELL CHEMISTRY EARTHING SYSTEM ELECTRIC LAMP ENERGY SOURCE FUNDAMENTAL OF ELECTRICITY 2 BIPOLAR JUNCTION TRANSISTOR 555 TIMER CIRCUITS AUTOCAD C PROGRAMMING HYDRO POWER LOGIC GATES OPERATIONAL AMPLIFIER`S SOLID-STATE DEVICE THEORRY DEFECE & MILITARY FLUORESCENT LAMP HOME AUTOMATION INDUSTRIAL ROBOTICS ANDROID COMPUTER ELECTRICAL DRIVES GROUNDING SYSTEM BLUETOOTH CALCULUS REFERENCE DC METERING CIRCUITS DC NETWORK ANALYSIS ELECTRICAL SAFETY TIPS ELECTRICIAN SCHOOL ELECTRON TUBES FUNDAMENTAL OF ELECTRICITY 1 INDUCTION MACHINES INSULATIONS ALGEBRA REFERENCE HMI[Human Interface Machines] INDUCTION MOTOR KARNAUGH MAPPING USEUL EQUIATIONS AND CONVERSION FACTOR ANALOG INTEGRATED CIRCUITS BASIC CONCEPTS AND TEST EQUIPMENTS DIGITAL COMMUNICATION DIGITAL-ANALOG CONVERSION ELECTRICAL SOFTWARE GAS TURBINE ILLUMINATION OHM`S LAW POWER ELECTRONICS THYRISTOR USB AUDIO BOOLEAN ALGEBRA DIGITAL INTEGRATED CIRCUITS FUNDAMENTAL OF ELECTRICITY 3 PHYSICS OF CONDUCTORS AND INSULATORS SPECIAL MOTOR STEAM POWER PLANTS TESTING TRANSMISION LINE C-BISCUIT CAPACITORS COMBINATION LOGIC FUNCTION COMPLEX NUMBERS ELECTRICAL LAWS HMI[HUMANI INTERFACE MACHINES INVERTER LADDER DIAGRAM MULTIVIBRATORS RC AND L/R TIME CONSTANTS SCADA SERIES AND PARALLEL CIRCUITS USING THE SPICE CIRCUIT SIMULATION PROGRAM AMPLIFIERS AND ACTIVE DEVICES BASIC CONCEPTS OF ELECTRICITY CONDUCTOR AND INSULATORS TABLES CONDUITS FITTING AND SUPPORTS CONTROL MOTION ELECTRICAL INSTRUMENTATION SIGNALS ELECTRICAL TOOLS INDUCTORS LiDAR MAGNETISM AND ELECTROMAGNETISM PLYPHASE AC CIRCUITS RECLOSER SAFE LIVING WITH GAS AND LPG SAFETY CLOTHING STEPPER MOTOR SYNCHRONOUS MOTOR AC METRING CIRCUITS APPS & SOFTWARE BASIC AC THEORY BECOME AN ELECTRICIAN BINARY ARITHMETIC BUSHING DIGITAL STORAGE MEMROY ELECTRICIAN JOBS HEAT ENGINES HOME THEATER INPECTIONS LIGHT SABER MOSFET NUMERATION SYSTEM POWER FACTORS REACTANCE AND IMPEDANCE INDUCTIVE RESONANCE SCIENTIFIC NOTATION AND METRIC PREFIXES SULFURIC ACID TROUBLESHOOTING TROUBLESHOOTING-THEORY & PRACTICE 12C BUS APPLE BATTERIES AND POWER SYSTEMS ELECTROMECHANICAL RELAYS ENERGY EFFICIENCY-LIGHT INDUSTRIAL SAFETY EQUIPMENTS MEGGER MXED-FREQUENCY AC SIGNALS PRINCIPLE OF DIGITAL COMPUTING QUESTIONS REACTANCE AND IMPEDANCE-CAPATIVE RECTIFIER AND CONVERTERS SEQUENTIAL CIRCUITS SERRIES-PARALLEL COMBINATION CIRCUITS SHIFT REGISTERS BUILDING SERVICES COMPRESSOR CRANES DC MOTOR DRIVES DIVIDER CIRCUIT AND KIRCHHOFF`S LAW ELECTRICAL DISTRIBUTION EQUIPMENTS 1 ELECTRICAL DISTRIBUTION EQUIPMENTS B ELECTRICAL TOOL KIT ELECTRICIAN JOB DESCRIPTION LAPTOP THERMOCOUPLE TRIGONOMENTRY REFERENCE UART WIRELESS BIOMASS CONTACTOR ELECTRIC ILLUMINATION ELECTRICAL SAFETY TRAINING FILTER DESIGN HARDWARE INDUSTRIAL DRIVES JUNCTION FIELD-EFFECT TRANSISTORS NASA NUCLEAR POWER SCIENCE VALVE WWE oscilloscope 3D TECHNOLOGIES COLOR CODES ELECTRIC TRACTION FEATURED FLEXIBLE ELECTRONICS FLUKE GEARMOTORS INTRODUCTION LASSER MATERIAL PID PUMP SEAL ELECTRICIAN CAREER ELECTRICITY SUPPLY AND DISTRIBUTION MUSIC NEUTRAL PERIODIC TABLES OF THE ELEMENTS POLYPHASE AC CIRCUITS PROJECTS REATORS SATELLITE STAR DELTA VIBRATION WATERPROOF