Embedded System Project 7: ESP32 Bluetooth Classic and Low Energy

Michelle Lim
9 min readMar 26, 2023

--

Hi, I’m Michelle and today I’ll be continuing my blog series of the embedded systems project! ✨🤩 (You can read the previous blog here 🤗)

The seventh project I’ll be doing is about Bluetooth classic and low energy using ESP32. Bluetooth is a connection oriented technology. This means that connection needs to be established first between Bluetooth compliant devices for data transfer to take place. Bluetooth uses low-energy radio waves to send wireless data between Bluetooth-enabled devices. In this, Bluetooth is similar to Wi-Fi that also operates over radio waves, however, Bluetooth can work between any two enabled devices and does not require additional network equipment such as routers or modems, making it a popular choice for sending data between mobile electronics over close ranges. Bluetooth works over a maximum distance of 50 meters between devices, a range that is more than enough for many home, car, health and consumer electronics applications.

Bluetooth version 4.0 is known as Bluetooth Low Energy or BLE. It is also referred by other names such as Bluetooth smart or Wibree. It is the low power variation of original traditional Bluetooth standard. Like Bluetooth, it is also managed and maintained by Bluetooth SIG. Due to low power consumption and low power sleep modes. Furthermore, it operates in the same band as standard Bluetooth but uses different FHSS scheme. As BLE devices are incompatible with standard Bluetooth devices, they will not inter-operate with them. Just like Bluetooth, BLE operates in the 2.4 GHz ISM band. Unlike classic Bluetooth, however, BLE remains in sleep mode constantly except for when a connection is initiated. The actual connection times are only a few ms, unlike Bluetooth which would take ~100ms. The reason the connections are so short, is that the data rates are so high at 1 Mb/s.

There are several differences between the Bluetooth Classic and the BLE. First, they are used for very different purposes. Bluetooth can handle a lot of data, but consumes battery life quickly and costs a lot more. Meanwhile, the BLE is used to data applications that do not need to exchange large amounts of data, and can therefore run on battery power for years at a cheaper cost. Second, the network and topology used are different. Both Bluetooth and BLE are Wireless Personal Area Network (WPAN) standards. BLE is developed to send small chunks of data. It’s designed to run IoT devices using coin cells. The network/topology used in Bluetooth is point-to-point while in BLE is broadcast or mesh. Third, the number of nodes or active slaves are different. As we know, Bluetooth is used for network requiring data exchange as well as wireless headset and other consumer devices. While BLE is used for applications such as mobile payment, healthcare, ticketing or access control. Both technology based devices are low cost and both Bluetooth and BLE networks consist of master and slave devices. In this, the nodes/active slaves in Bluetooth is 7 while in BLE is unlimited.

The ESP32 comes with Wi-Fi, Bluetooth Low Energy and Bluetooth Classic. In these two projects, we will be exploring the BLE and Bluetooth Classic.

Project 1: Introduction

For the first project, we’ll be using Bluetooth Classic to exchange data between the ESP32 and the Android smartphone.

The components we’ll be using in these projects are listed below.

  1. ESP32 Development Board
  2. Micro-USB Cable
  3. Breadboard
  4. 5mm LEDs
  5. an Android smartphone
  6. Male-to-Male jumper wires
  7. Laptop/PC with Arduino IDE installed and set

Project 1: Serial to Serial Bluetooth

Follow the steps below in doing the first project. 😄

1. Install the Bluetooth Terminal application on your (preferably Android) smartphone.

It is recommended to use the Android app “Serial Bluetooth Terminal” available in Play Store.

Serial Bluetooth Terminal app on Play Store

2. Open your Arduino IDE and open the example code provided by going to File > Examples > BluetoothSerial > SerialtoSerialBT.

File > Examples > BluetoothSerial > SerialtoSerialBT

A new window should open with the following code loaded.

//This example code is in the Public Domain (or CC0 licensed, at your option.)
//By Evandro Copercini - 2018
//
//This example creates a bridge between Serial and Classical Bluetooth (SPP)
//and also demonstrate that SerialBT have the same functionalities of a normal Serial

#include "BluetoothSerial.h"

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

BluetoothSerial SerialBT;

void setup() {
Serial.begin(115200);
SerialBT.begin("ESP32test"); //Bluetooth device name
Serial.println("The device started, now you can pair it with bluetooth!");
}

void loop() {
if (Serial.available()) {
SerialBT.write(Serial.read());
}
if (SerialBT.available()) {
Serial.write(SerialBT.read());
}
delay(20);
}

Code explanation: The #include “BluetoothSerial.h” includes the BluetoothSerial library. Then, the next three lines check if Bluetooth is properly enabled. We then create an instance of BluetoothSerial called SerialBT in BluetoothSerial SerialBT. The setup() initializes a serial communication at a baud rate of 115200. It also initializes the Bluetooth serial device and pass as an argument the Bluetooth Device name. By default it’s called ESP32test but you can rename it and give it a unique name. The loop() then sends and receives data via Bluetooth Serial.

3. Connect your ESP32, compile and upload the code, and open the Serial Monitor at a baud rate of 115200. Press the ESP32 Enable button.

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

Device started printed on serial monitor

4. Enable bluetooth on your smartphone and pair the ESP32.

Pair smartphone with ESP32test

5. Connect to the ESP32.

Open the app > Click ESP32test > Click on the top button circled on the picture below. You should then get a “Connected” message.

Connected to ESP32test

6. Try exchanging message between two devices.

Type something in the Serial Bluetooth Terminal app, and you should instantly receive that message in the Arduino IDE Serial Monitor. You can also send the message from the Serial Monitor, and instantly receive that message in the Serial Bluetooth Terminal app on your smartphone. 😄

Smartphone to ESP32
ESP32 to Smartphone

Project 1: Turning On and Off LED from Smartphone

Follow these steps for the second part of the project! 😊

1. Arrange the schematic according to the picture attached below.

Schematic arrangement with LED

Pinout:

  1. ESP32 GND pin — Breadboard negative pole
  2. ESP32 3V3 pin — Breadboard positive pole
  3. ESP32 GPIO5 pin — LED positive pin
  4. LED negative pin — Breadboard negative pole

Your arrangement should look like this.

My arrangement for reference

2. Set the value of M1 and M2 button of the Serial Bluetooth Terminal app.

Set value of M1 and M2 button

3. Copy, compile, and upload the code below.

#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;
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() {
unsigned long currentMillis = millis();
// 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);
}

4. Click the M1 and M2 buttons!

You should then get the LED turn on and off as shown on the gif attached below. 😆

LED turning on and off based on the button clicked.

Project 2: Introduction

For the second project, we’ll be creating an ESP32 BLE server and use our smartphone to scan it and see its services and characteristics.

The components we’ll be using in these projects are listed below.

  1. ESP32 Development Board
  2. Micro-USB Cable
  3. Breadboard
  4. an Android smartphone
  5. Laptop/PC with Arduino IDE installed and set

Project 2: ESP32 BLE Server

Follow these steps below to test your ESP32 BLE Server with Smartphone! 😄

1. Install the “nRF Connect for Mobile” from Nordic on your smartphone.

The app is available on both iOS App Store and Android Google Play Store. It will be used to scan the ESP32 BLE server with your smartphone.

Note: Don’t forget to enable Bluetooth and pair the ESP32 like on the first project.

nRF Connect for Mobile on Google Play Store

2. Open your Arduino IDE and go to File > Examples > ESP32 BLE Arduino > BLE_server.

File > Examples > ESP32 BLE Arduino > BLE_server

A new window should open with the following code loaded.

/*
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 Michelle");
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);
}

Code explanation: It starts by importing the necessary libraries for the BLE capabilities. Then, it defines a UUID for the Service and Characteristic. In the setup(), it starts the serial communication at a baud rate of 115200, create a BLE device, and set the BLE device as a server. After that, you create a service for the BLE server with the UUID defined earlier. Then, set the characteristic for that service. After that, set its value with the setValue() method. Finally, you can start the service, and the advertising, so other BLE devices can scan and find this BLE device.

3. Copy, compile and upload the code.

4. Open the nRF Connect for Mobile app on your smartphone, Check the Bonded section, and Click on CONNECT for the ESP32.

Connect to ESP32

5. Look at the new tab of ESP32 opened.

ESP32 BLE Server shown on app

As seen in the picture above, the ESP32 has a service with the UUID that we’ve defined earlier. When we tap the service, it expands the menu and shows the Characteristic with the UUID that we’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. 😉👍

So yea, that’s the end of our seventh Embedded System Project: ESP32 Bluetooth Classic and Low Energy. (yeah!! 🥳) Stay tune for the next projects and stay safe and healthy 🥰

--

--