Project 7 : Connecting ESP32 and our smartphone with bluetooth connection

 ๐Ÿ˜€๐Ÿ˜๐Ÿ˜‚๐Ÿ˜ƒ๐Ÿ˜„๐Ÿ˜…๐Ÿ˜†๐Ÿ˜‡๐Ÿ˜ˆ๐Ÿ˜‰๐Ÿ˜Š๐Ÿ˜‹๐Ÿ˜Œ๐Ÿ˜๐Ÿ˜Ž๐Ÿ˜๐Ÿ˜๐Ÿ˜‘๐Ÿ˜’๐Ÿ˜“๐Ÿ˜”๐Ÿ˜•๐Ÿ˜–๐Ÿ˜—๐Ÿ˜˜๐Ÿ˜™๐Ÿ˜š๐Ÿ˜›๐Ÿ˜œ๐Ÿ˜

Starting a project is no small feat,

It takes a plan and lots of heat.

Gather ideas and get them neat,

Then put them down, don't miss a beat.


With every step, keep moving forward,

Don't let obstacles make you cornered.

Stay focused and you'll be rewarded,

A successful project is what's ordered.

๐Ÿ˜ž๐Ÿ˜Ÿ๐Ÿ˜ ๐Ÿ˜ก๐Ÿ˜ข๐Ÿ˜ฃ๐Ÿ˜ค๐Ÿ˜ฅ๐Ÿ˜ฆ๐Ÿ˜ง๐Ÿ˜จ๐Ÿ˜ฉ๐Ÿ˜ช๐Ÿ˜ซ๐Ÿ˜ฌ๐Ÿ˜ญ๐Ÿ˜ฎ๐Ÿ˜ฏ๐Ÿ˜ฐ๐Ÿ˜ฑ๐Ÿ˜ฒ๐Ÿ˜ณ๐Ÿ˜ด๐Ÿ˜ต๐Ÿ˜ถ๐Ÿ˜ธ๐Ÿ˜ท๐Ÿ˜น๐Ÿ˜บ๐Ÿ˜ป

๐Ÿ‘‹๐Ÿ‘‹๐Ÿ‘‹ Hallo guys, welcome back to my blogspot. This time we will create an ESP32 project with bluetooth. There are two project variations that will be discussed, the first is ESP32 Bluetooth Classic with Arduino IDE and ESP32 Bluetooth Low Energy (BLE) on Arduino IDE. These two projects are quite interesting projects because we can do many things with a Bluetooth connection between our ESP32 and our device (in this project, our smartphone). To make a connection between the ESP32 and our smartphone, we need an intermediary application, namely the Serial Bluetooth Terminal application, which we can download in the playstore. For that without lingering any longer we just go into the project! ๐Ÿ˜€



▀▄▀▄▀▄========================================================▀▄▀▄▀▄

๐Ÿ”ŽSET UP๐Ÿ”Ž

1. 2 Pcs of ESP32

2. 1 Pcs Of .Barometetric Pressure Sensor (BMP280)


3.1 Pcs of Breadboard
4. 4 Pcs of Male to Female Cable Jumper


5.  1 Pcs of Male to Male Cable Jumper


6. 2 Pcs of Micro USB cable

7. 3 Pcs of 5 mm LED







 8. Pcs of 10k ohm resistor





1.ESP32 Bluetooth Classic with Arduino IDE


๐Ÿ‘ฃ STEP BY STEP ๐Ÿ‘ฃ

1.Download serial bluetooth terminal in playstore on your smartphone .




2.Open your Arduino IDE, and go to File -> Examples -> BluetoothSerial -> SerialtoSerialBT.


3.
Make sure you have the right board and COM port selected (in this case i used COM3 port)



4.Click the Upload button and wait a few seconds for the words "Leaving... Hard resetting via RTS pin..." to display. 




5.Then, open Tools > Serial Monitor at a baud rate of 115200. 

6.Press the ESP32 Enable button which is indicated with "EN" button on your ESP32.



6.After a few seconds, you should get a message saying: “The device started, now you can pair it with bluetooth!”.


7.Download Serial Bluetooth Terminal in goole playstore  or appstore (in this project i download it from google playstore).


8.After the donwload finished , open the “Serial Bluetooth Terminal” app. Go to Device section


9. Click the three dots icon then click bluetooth .


9. Connect to ESP32test bluetooth option.


10. Go back to device section and click ESP32test.


11.Then, go back to the Serial Bluetooth Terminal. Click the icon at the top to connect to the ESP32. You should get a “Connected” message.


12.After that, type something in the Serial Bluetooth Terminal app then click send button. For example, “Hallo”.


13.You should instantly receive that message in the Arduino IDE Serial Monitor at the same time.



14.We can also exchange data between our Serial Monitor and our smartphone. Type something in the Serial Monitor top bar and press the “Enter” button in your keyboard.


15.You should instantly receive that message in the Serial Bluetooth Terminal App (In this case i send "Hello from PC" twice).


Exchange Data using Bluetooth Serial

"This project will show where when we provide input in the form of text "led_on" to the Serial Bluetooth Terminal on Android, the lights on the circuit will turn on, then when we provide input in the form of text "led_off" on the Serial Bluetooth Terminal on Android, then the lights on the circuit will go out. The temperature reading will always be displayed on the serial monitor on the arduino IDE and the serial bluetooth terminal on our android"

๐Ÿ‘ฃSTEP BY STEP๐Ÿ‘ฃ

1.Before proceeding with this project, assemble the circuit by following the next schematic diagram.


๐Ÿ‘‡To see the circuit configuration more clearly, I made a pin table to make it easier for friends ๐Ÿ‘‡ 
to arrange the circuit


2.Adopt this code below.
/*********
  Rui Santos
  Complete project details at https://randomnerdtutorials.com
*********/

// Load libraries
#include "BluetoothSerial.h"


// Check if Bluetooth configs are enabled
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

// Bluetooth Serial object
BluetoothSerial SerialBT;

// GPIO where LED is connected to
const int ledPin =  25;

// Handle received and sent messages
String message = "";
char incomingChar;
String temperatureString = "";

// Timer: auxiliar variables
unsigned long previousMillis = 0;    // Stores last time temperature was published
const long interval = 1000;         // interval at which to publish sensor readings
     

#include <Wire.h>             // include Wire library, required for I2C devices
#include <Adafruit_Sensor.h>  // include Adafruit sensor library
#include <Adafruit_BMP280.h>  // include adafruit library for BMP280 sensor
 
// define device I2C address: 0x76 or 0x77 (0x77 is library default address)
#define BMP280_I2C_ADDRESS  0x76
 
Adafruit_BMP280 bmp280;


void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(115200);
  // Bluetooth device name
  SerialBT.begin("ESP32");
  Serial.println("The device started, now you can pair it with bluetooth!");
  Serial.println(F("Arduino + BMP280"));
 
  if (!bmp280.begin(BMP280_I2C_ADDRESS))
  {  
    Serial.println("Could not find a valid BMP280 sensor, check wiring!");
    while (1);
  }
  Serial.println("Found BMP280 sensor!");
}

// void startend(String message , int start_temp , int led_status , float temperature){
 
 
// }
 

void loop() {

unsigned long currentMillis = millis();


if (currentMillis - previousMillis >= interval){
previousMillis = currentMillis;
float temperature = bmp280.readTemperature(); // Send temperature readings
temperatureString = "Temperature = " + String(temperature) + " °C";
SerialBT.println(temperatureString);
}
 
  // Read received messages (LED control command)
  if (SerialBT.available()){
    char incomingChar = SerialBT.read();
    if (incomingChar != '\n'){
      message += String(incomingChar);
    }
    else{
      message = "";
    }
    Serial.write(incomingChar);  
  }


  // Check received message and control output accordingly
  if (message == "led_on" ){
      digitalWrite(ledPin, HIGH);
  }
  else if (message =="led_off" ){
    digitalWrite(ledPin, LOW);
    }

  delay(20);
}


 

3.Click the Upload button and wait a few seconds for the words "Leaving... Hard resetting via RTS pin..." to display. 


4.Press the ESP32 Enable button which is indicated with "EN" button on your ESP32.


5.When you receive the following message on your serial monitor on Tools > Serial Monitor with baud 115200, you can go to your smartphone and connect with the ESP32.



6.Then, you can write the“led_on” and “led_off” messages to control the LED in your serial bluetooth text box , then click send button.






7.For more detailed results, please see the following video from link below.


๐Ÿ”‘ MODIFIED PROJECT ๐Ÿ”‘

"This project modification will add a new feature, namely "start" and "stop" which indicate a program is started or stopped. When we enter the text "start" at the beginning of the program, the new program issues a temperature measurement that is read by the BMP280 sensor. Then when the temperature is above 30 degrees Celsius, the LED light will blink. After that, if we enter a text "stop" into the serial bluetooth monitor, we will terminate this program in the next few seconds."

๐Ÿ‘ฃSTEP BY STEP๐Ÿ‘ฃ

1.Arrange the same scheme as the previous section

2.Adopt this code below.


/*********
  Rui Santos
  Complete project details at https://randomnerdtutorials.com
*********/

// Load libraries
#include "BluetoothSerial.h"


// Check if Bluetooth configs are enabled
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

// Bluetooth Serial object
BluetoothSerial SerialBT;

// GPIO where LED is connected to
const int ledPin =  25;


int start_temp = 0;  // Menandakan bahwa kapan program dimulai
int led_status = 0;  // Menandakan bahwa kapan lampu akan berkelap kelip

// Handle received and sent messages
String message = "";
char incomingChar;
String temperatureString = "";

// Timer: auxiliar variables
unsigned long previousMillis = 0;    // Stores last time temperature was published
const long interval = 1000;         // interval at which to publish sensor readings
     

#include <Wire.h>             // include Wire library, required for I2C devices
#include <Adafruit_Sensor.h>  // include Adafruit sensor library
#include <Adafruit_BMP280.h>  // include adafruit library for BMP280 sensor
 
// define device I2C address: 0x76 or 0x77 (0x77 is library default address)
#define BMP280_I2C_ADDRESS  0x76
 
Adafruit_BMP280 bmp280;


void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(115200);
  // Bluetooth device name
  SerialBT.begin("ESP32");
  Serial.println("The device started, now you can pair it with bluetooth!");
  Serial.println(F("Arduino + BMP280"));
 
  if (!bmp280.begin(BMP280_I2C_ADDRESS))
  {  
    Serial.println("Could not find a valid BMP280 sensor, check wiring!");
    while (1);
  }
  Serial.println("Found BMP280 sensor!");
}

// void startend(String message , int start_temp , int led_status , float temperature){
 
 
// }
 

void loop() {
  float temperature = bmp280.readTemperature();
  Serial.print("led_status");
  Serial.println(led_status);
  Serial.print("start_temp");    
  Serial.println(start_temp);
  Serial.print("message");
  Serial.println(message);  
  // Read received messages (LED control command)
  if (SerialBT.available()){
    char incomingChar = SerialBT.read();
    if (incomingChar != '\n'){
      message += String(incomingChar);
    }
    else{
      message = "";
    }
    Serial.write(incomingChar);  
  }
    if(message == "start" || start_temp == 1){
    unsigned long currentMillis = millis();
    // Send temperature readings
    Serial.println("Masuk");      
    if (currentMillis - previousMillis >= interval){
    previousMillis = currentMillis;
    temperatureString = "Temperature = " + String(temperature) + " °C";
    SerialBT.println(temperatureString);
    }
    start_temp = 1;    
  }
  // Check received message and control output accordingly
  if (message == "led_on" || led_status == 1){
    Serial.println("Masuk2");
    if(temperature > 30.0){
      digitalWrite(ledPin, HIGH);
      delay(500);
      digitalWrite(ledPin, LOW);
      delay(500);
      digitalWrite(ledPin, HIGH);
    }
    else{
      digitalWrite(ledPin, HIGH);
    }
    led_status = 1;
  }
  if (message =="led_off" || led_status == 0){
    Serial.println("Masuk 3");
    digitalWrite(ledPin, LOW);
    led_status = 0;
    }
  // else if (message == "stop" || start_temp == 0){
  //   start_temp = 0;
  //   led_status = 0;  
  // }
    if(message == "stop" || start_temp == 0){
    start_temp = 0;
    led_status = 0;  
  }
 


  // startend( message ,  start_temp ,  led_status , temperature);
  Serial.print("start_temp end :");    
  Serial.println(start_temp);
  delay(20);
}

3.Do the same thing in steps 3 to 5 according to the procedure in the previous section

4.Then, you can write the "start" to display the meausrement and you can write “led_on”to turn on the LED .  and “led_off” messages to control the LED in your serial bluetooth text box , then click send button. When the temperature read by the BMP 280 sensor is above 30 degrees Celsius, the LED will blink, while if the temperature is below or equal to 30 degrees Celsius, the lights will continue to turn on




5.Then write "turn_off" to turn off the light or "stop" to turn off the light and display the temperature reading.


In this case, the program stops after taking temperature readings 4 times after the word "stop" is inputted to the terminal. This can happen because of the code modification error that I have done. The program should stop immediately when the word "stop" is inputted into the terminal.

6.For more detailed results, please see the following video from link below.


2.ESP32 Bluetooth Low Energy (BLE) Project

"This project will talk about how ESP32 acts as a server that is ready to receive and open connections to various devices that can be connected to each other."


【๏ผฅ๏ผณ๏ผฐ๏ผ“๏ผ’ ๏ผข๏ผฌ๏ผฅ ๏ผณ๏ฝ…๏ฝ’๏ฝ–๏ฝ…๏ฝ’】 

๐Ÿ‘ฃSTEP BY STEP๐Ÿ‘ฃ

1.Open your Arduino IDE

2. Go to File > Examples > ESP32 BLE Arduino and select the BLE_server example



3.The code you should have is like this

/*
    Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleServer.cpp
    Ported to Arduino ESP32 by Evandro Copercini
    updates by chegewara
*/

#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>

// See the following for generating UUIDs:
// https://www.uuidgenerator.net/

#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"

void setup() {
  Serial.begin(115200);
  Serial.println("Starting BLE work!");

  BLEDevice::init("Marvel's ESP32");
  BLEServer *pServer = BLEDevice::createServer();
  BLEService *pService = pServer->createService(SERVICE_UUID);
  BLECharacteristic *pCharacteristic = pService->createCharacteristic(
                                         CHARACTERISTIC_UUID,
                                         BLECharacteristic::PROPERTY_READ |
                                         BLECharacteristic::PROPERTY_WRITE
                                       );

  pCharacteristic->setValue("Hello Marvel");
  pService->start();
  // BLEAdvertising *pAdvertising = pServer->getAdvertising();  // this still is working for backward compatibility
  BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
  pAdvertising->addServiceUUID(SERVICE_UUID);
  pAdvertising->setScanResponse(true);
  pAdvertising->setMinPreferred(0x06);  // functions that help with iPhone connections issue
  pAdvertising->setMinPreferred(0x12);
  BLEDevice::startAdvertising();
  Serial.println("Hellow Marvel");
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(2000);
}

4.Click the Upload button and wait a few seconds for the words "Leaving... Hard resetting via RTS pin..." to display. 


5.In this case, ESP32 will act as a server by clicking the "EN" button which means "Enable".


6.For this reason, to prove that ESP32 is already acting as a server, we will use our smartphone as a client and connect our BMP with our smartphone. We will continue with the testing the ESP32 BLE Server with Smartphone project .


【๏ผด๏ฝ…๏ฝ“๏ฝ”๏ฝ‰๏ฝŽ๏ฝ‡ ๏ฝ”๏ฝˆ๏ฝ… ๏ผฅ๏ผณ๏ผฐ๏ผ“๏ผ’ ๏ผข๏ผฌ๏ผฅ ๏ผณ๏ฝ…๏ฝ’๏ฝ–๏ฝ…๏ฝ’ ๏ฝ—๏ฝ‰๏ฝ”๏ฝˆ ๏ผณ๏ฝ๏ฝ๏ฝ’๏ฝ”๏ฝ๏ฝˆ๏ฝ๏ฝŽ๏ฝ…】 

"This project will continue the previous project where we will connect our smartphone with the previous ESP32 method which is setup as a server"

๐Ÿ‘ฃSTEP BY STEP๐Ÿ‘ฃ

1.Continuing the steps of the ESP32 Bluetooth Low Energy (BLE) Project above, then next we will download the nRF Connect application on the Playstore. In this case I use the device redmi note 8 (xiaomi).


2.Open the nRF Connect app

3. Search for Device ESP32 in the application. The name of our ESP32 device will appear in accordance with the name we have setup in the previous section, namely
// Create the BLE Device
  BLEDevice::init("Marvel's ESP32");




4.Then tap "CONNECT" button.

5.Go to the "Client" tab on the navigation bar . As you can see in the figure below, the ESP32 has a service with the UUID that you've defined earlier. If you tap the service, it expands the menu and shows the Characteristic with the UUID that you've also defined. The characteristic has the READ and WRITE properties, and the value is the one we've previously defined in the BLE server sketch. So, everything is working fine.






3.ESP32 BLE Scanner

"This project talks about how to make an ESP32 act as a client looking for connections to other devices. In this case we need 2 different ESP32s to run the previous project where the ESP32 acts as a server and one acts as a client."

๐Ÿ‘ฃSTEP BY STEP๐Ÿ‘ฃ

1.Open your Arduino IDE, go to File > Examples > ESP32 BLE Arduino and select the BLE_scan example. The following code below should load

/*
   Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleScan.cpp
   Ported to Arduino ESP32 by Evandro Copercini
*/

#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>

int scanTime = 5; //In seconds
BLEScan* pBLEScan;

class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
    void onResult(BLEAdvertisedDevice advertisedDevice) {
      Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str());
    }
};

void setup() {
  Serial.begin(115200);
  Serial.println("Scanning...");

  BLEDevice::init("");
  pBLEScan = BLEDevice::getScan(); //create new scan
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster
  pBLEScan->setInterval(100);
  pBLEScan->setWindow(99);  // less or equal setInterval value
}

void loop() {
  // put your main code here, to run repeatedly:
  BLEScanResults foundDevices = pBLEScan->start(scanTime, false);
  Serial.print("Devices found: ");
  Serial.println(foundDevices.getCount());
  Serial.println("Scan done!");
  pBLEScan->clearResults();   // delete results fromBLEScan buffer to release memory
  delay(2000);
}


2.Click the Upload button and wait a few seconds for the words "Leaving... Hard resetting via RTS pin..." to display. 


3.In this project, we need 2 ESP32s that have been powered on
a.ESP32 with the “BLE_server” sketch;
b.Other ESP32 with “BLE_scan” sketch.


4.For other ESP32s, use a laptop or other device to become a power supply for other ESP32s. Then repeat the same thing on the other ESP32 according to the steps on the ESP32 Bluetooth Low Energy (BLE) Project above that we have made. In this case the code from "BLE_server" that changes is only in the set up device name, namely the code as follows.
// Create the BLE Device
  BLEDevice::init("another ESP32 device");


5.press the ESP32 (with the “BLE_scan” sketch) ENABLE button by pressing the button marked "EN" on our ESP32 devic and wait a few seconds while it scans.


6.To see the output, we can see it by going to Tools > Serial Monitor, then selecting the 115200 baud series.



From the red boxed image above, we can see that our ESP32 (with BLE_scan sketch) is scanning and searching to make connections with other devices to our ESP32. In this case, it can be seen that another ESP32 (with BLE_server) that functions as a server is detected by our ESP32 (with BLE_scan) with a device name that matches the name we have previously setup, namely "another ESP32 device".

๐ŸŽ‰๐ŸฅณHooray, we've finished the project


๐Ÿ˜„That's all from me ๐Ÿ‘Œ

๐Ÿ‘‹ See you in my next blog with ESP32. 

๐Ÿ‘‹ Bye Bye !

Comments