ESP32 Bluetooth Communication

Welcome back to my blog! This week, I'm going to try experimenting with one of the wireless connections, Bluetooth. ESP32 has a built-in Bluetooth feature so we can readily use it. There are two kinds of Bluetooth connections:

1. Bluetooth classic, used for a wireless headset, speaker, or microphone

2. Bluetooth low energy, used for wearable devices such as health band

Bluetooth Classic

Now, let's experiment with the classic one first!

First, you need to prepare a Bluetooth Terminal application for your smartphone. I'm using this Android application called "Serial Bluetooth Terminal" that you can download in Play Store.

You also have to prepare the components (you'll use these components for all experiments for this week):

1. ESP32

2. Laptop/PC

3. Micro USB

4. Breadboard

5. Male-to-male jumper

6. LED

7. 330-ohm resistor

8. Smartphone

Before starting the project to exchange data, we can test the Bluetooth connection first. 

1. Connect ESP32 with a laptop/PC using a micro USB cable

2. Open Arduino IDE

3. Find the test code in File > Examples > BluetoothSerial > SerialToSerialBT


4. Upload the code to ESP32

5. Open Serial Monitor in Arduino IDE (Tools > Serial Monitor) and set the baud rate to 115200

6. Press the EN (enable) button on ESP32

7. If you see this message on Serial Monitor, then you can proceed to pair it with your smartphone that has Serial Bluetooth Monitor installed

8. Open Serial Bluetooth Monitor on your phone, don't forget to turn on your Bluetooth

9. Pair with ESP32test

10. Open Devices and choose ESP32test

11. After it's connected, try writing a message and sending it


12. From Serial Monitor, reply to the message


See if you've received the message on your phone

Done!

After you're done testing and connecting ESP32 with Bluetooth, we can try to exchange data using Bluetooth Serial. Prepare the circuit like this.

Follow these steps:

1. Open Arduino IDE

2. Copy this code

/*********

  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 =  5;


// Handle received and sent messages

String message = "";

char incomingChar;

String temperatureString = "";


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!");

}


void loop() {


  // 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. Upload the code to ESP32

4. Open Serial Monitor. Set the baud rate to 115200

5. Press EN (enable) button on ESP32

6. If you see this message on Serial Monitor, then you can start pairing it to your phone.

7. Open the Serial Bluetooth Terminal on your phone. Don't forget to turn on the Bluetooth.

8. Press the connect button on your phone.

9. When the ESP32 is connected to the phone, you can start sending messages to turn on and off the LED.




10. You can also make associate the messages with the buttons to save them as default messages. For example, I'm making M1 as "led_on" and M2 as "led_off". Now you can just press the buttons to control the LED.


Bluetooth Low Energy

Bluetooth Low Energy is the power-conserving variant of Bluetooth and is often used in the short-distance transmission of small amounts of data. Let's try implementing it in ESP32 by creating an ESP32 BLE server and connecting it with a smartphone.

1. Open Arduino IDE

2. Find the example code in File > Examples > ESP32 BLE Arduino > BLE_server

or copy this code

/*

    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("Long name works now");

  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 World says Neil");

  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("Characteristic defined! Now you can read it in your phone!");

}


void loop() {

  // put your main code here, to run repeatedly:

  delay(2000);

}

3. Open Serial Monitor and set the baud rate to 115200

4. Press enable button on ESP32 and see this on your Serial Monitor

5. Install nRF Connect for Mobile on your smartphone and open it.

6. Enable your phone's Bluetooth.

7. Scan for nearby devices by tapping the SCAN button.

8. Connect with your ESP32, for me, the name is "Long name works now" because of the init code

9. Open the tab for the ESP32. You can see that the ESP32 has a service with the UUID that was defined earlier. 

10. Tap the service to show the Characteristics. Tap the download button to see the value.

Yay! You've send the message "Hello World says Niel"

That's it! Hope this helps :)

Comments

Popular posts from this blog

ESP32 OLED Display and ESP32 PWM

Blinking LED on ESP32

ESP32 I2C Serial Communication