Hello

Welcome lekule blog

Hi, I`m Sostenes, Electrical Technician and PLC`S Programmer.
Everyday I`m exploring the world of Electrical to find better solution for Automation.
together in the world. #lekule86
Join us on

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.

Share this:

ABOUTME

Hi all. This is deepak from Bthemez. We're providing content for Bold site and we’ve been in internet, social media and affiliate for too long time and its my profession. We are web designer & developer living India! What can I say, we are the best..

Post a Comment
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.

Labels

LEKULE TV EDITORIALS ARTICLES DC ROBOTICS DIGITAL SEMICONDUCTORS GENERATOR AC EXPERIMENTS MANUFACTURING-ENGINEERING REFERENCE FUNDAMENTAL OF ELECTRICITY ELECTRONICS ELECTRICAL ENGINEER MEASUREMENT TRANSDUCER & SENSOR VIDEO ARDUINO RENEWABLE ENERGY AUTOMOBILE TEARDOWN SYNCHRONOUS GENERATOR DIGITAL ELECTRONICS ELECTRICAL DISTRIBUTION CABLES AUTOMOTIVE MICROCONTROLLER SOLAR PROTECTION DIODE AND CIRCUITS BASIC ELECTRICAL ELECTRONICS MOTOR SWITCHES CIRCUIT BREAKERS CIRCUITS THEORY PANEL BUILDING ELECTRONICS DEVICES MIRACLES SWITCHGEAR ANALOG MOBILE DEVICES WEARABLES CAMERA TECHNOLOGY COMMUNICATION GENERATION BATTERIES FREE CIRCUITS INDUSTRIAL AUTOMATION SPECIAL MACHINES ELECTRICAL SAFETY ENERGY EFFIDIENCY-BUILDING DRONE CONTROL SYSTEM NUCLEAR ENERGY SMATRPHONE FILTER`S POWER BIOGAS BELT CONVEYOR MATERIAL HANDLING RELAY ELECTRICAL INSTRUMENTS ENERGY SOURCE 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 CELL CHEMISTRY EARTHING SYSTEM ELECTRIC LAMP FUNDAMENTAL OF ELECTRICITY 2 BIPOLAR JUNCTION TRANSISTOR 555 TIMER CIRCUITS AUTOCAD BLUETOOTH C PROGRAMMING HOME AUTOMATION HYDRO POWER LOGIC GATES OPERATIONAL AMPLIFIER`S SOLID-STATE DEVICE THEORRY COMPUTER DEFECE & MILITARY FLUORESCENT LAMP INDUSTRIAL ROBOTICS ANDROID ELECTRICAL DRIVES GROUNDING SYSTEM CALCULUS REFERENCE DC METERING CIRCUITS DC NETWORK ANALYSIS ELECTRICAL SAFETY TIPS ELECTRICIAN SCHOOL ELECTRON TUBES FUNDAMENTAL OF ELECTRICITY 1 INDUCTION MACHINES INSULATIONS USB 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 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 CONTROL MOTION ELECTRICAL LAWS 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 APPS & SOFTWARE BASIC CONCEPTS OF ELECTRICITY CONDUCTOR AND INSULATORS TABLES CONDUITS FITTING AND SUPPORTS 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 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 RECTIFIER AND CONVERTERS RESONANCE SCIENTIFIC NOTATION AND METRIC PREFIXES SULFURIC ACID TROUBLESHOOTING TROUBLESHOOTING-THEORY & PRACTICE 12C BUS APPLE BATTERIES AND POWER SYSTEMS DC MOTOR DRIVES ELECTROMECHANICAL RELAYS ENERGY EFFICIENCY-LIGHT INDUSTRIAL SAFETY EQUIPMENTS MEGGER MXED-FREQUENCY AC SIGNALS PRINCIPLE OF DIGITAL COMPUTING QUESTIONS REACTANCE AND IMPEDANCE-CAPATIVE SEQUENTIAL CIRCUITS SERRIES-PARALLEL COMBINATION CIRCUITS SHIFT REGISTERS WIRELESS BUILDING SERVICES COMPRESSOR CRANES DIVIDER CIRCUIT AND KIRCHHOFF`S LAW ELECTRICAL DISTRIBUTION EQUIPMENTS 1 ELECTRICAL DISTRIBUTION EQUIPMENTS B ELECTRICAL TOOL KIT ELECTRICIAN JOB DESCRIPTION INDUSTRIAL DRIVES LAPTOP SCIENCE THERMOCOUPLE TRIGONOMENTRY REFERENCE UART oscilloscope BIOMASS CONTACTOR ELECTRIC ILLUMINATION ELECTRICAL SAFETY TRAINING ELECTROMECHANICAL FEATURED FILTER DESIGN HARDWARE JUNCTION FIELD-EFFECT TRANSISTORS NASA NUCLEAR POWER VALVE COLOR CODES ELECTRIC TRACTION FLEXIBLE ELECTRONICS FLUKE GEARMOTORS INTRODUCTION LASSER 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