In this tutorial, I will share how to use the Bluetooth module with Arduino. We will learn how to send data, receive data from a phone, and also how to control Arduino from the phone.
This is a companion to a video on miliohm Youtube Channel. You can watch the full tutorial below.
Let’s start hookup the Bluetooth module with Arduino.
SPP-C and HC-05 Bluetooth with Arduino Wiring Diagram
The Code
#include <SoftwareSerial.h> SoftwareSerial mySerial(3, 4); //Rx,Tx void setup() { // put your setup code here, to run once: Serial.begin(9600); mySerial.begin(9600); } void loop() { if (mySerial.available()) { Serial.write(mySerial.read()); } if (Serial.available()) { mySerial.write(Serial.read()); } }
Upload the code above and now we can communicate Arduino and Bluetooth modules. We will communicate Arduino with a Bluetooth module using serial monitor. And these are some list AT commands we can use.
AT+NAME -> check the Bluetooth name
AT+VERSION -> Bluetooth version
AT+PIN -> Bluetooth pin
AT+BAUD -> Bluetooth baudrate
To Change the Bluetooth name you can type
AT+NAMEyourdesiredname
Now we will try to display text sent from phone to LCD. So let’s hook up an LCD to Arduino.
Bluetooth Module with LCD Wiring Diagram
In this example, the text from the phone that was sent with Bluetooth will be printed on LCD. if you need a detailed tutorial on I2C LCD you can find it here.
After the wiring with LCD is done, now you can use this code to print the text. And if your LCD at some point doesn’t print the value. Try to read my I2C LCD tutorial here.
#include <SoftwareSerial.h> #include <Wire.h> #include <LiquidCrystal_I2C.h> LiquidCrystal_I2C lcd(0x27,16,2); SoftwareSerial mySerial(3, 4); //Rx,Tx void setup() { // put your setup code here, to run once: Serial.begin(9600); mySerial.begin(9600); lcd.init(); lcd.backlight(); lcd.clear(); } void loop() { String data; if (mySerial.available()) { data += mySerial.readString(); data = data.subString(0, data.length() - 2); Serial.print(data); lcd.setCursor(0,0); lcd.print(data); } if (Serial.available()) { mySerial.write(Serial.read()); } }
Upload the program above, and you can use any serial app to Bluetooth. In this example I use android app called Serial Bluetooth Terminal. Any text you send from this app will shown on LCD.
Add LEDs to Control From Phone
#include <SoftwareSerial.h> SoftwareSerial mySerial(3, 4); //Rx,Tx void setup() { // put your setup code here, to run once: Serial.begin(9600); mySerial.begin(9600); pinMode(5, OUTPUT); pinMode(6, OUTPUT); pinMode(7, OUTPUT); } void loop() { if (mySerial.available()) { char data = mySerial.read(); Serial.print(data); if (data == '1') { digitalWrite(5, !(digitalRead(5))); } else if (data == '2') { digitalWrite(6, !(digitalRead(6))); } else if (data == '3') { digitalWrite(7, !(digitalRead(7))); } } if (Serial.available()) { mySerial.write(Serial.read()); } }
So when you send data 1 to Bluetooth, it will toggle first LED, 2 for second LED, and 3 is third LED.