ESP32 Project #7: Bluetooth

Chintya Wijaya
5 min readMar 20, 2021

Hello! On this project I’ll show how Bluetooth Classic and Bluetooth Low Energy work on ESP32. Bluetooth is used for wireless communication in personal area networks (PAN). Bluetooth is a wireless technology that uses low-energy radio waves to send wireless data between Bluetooth-enabled devices. Bluetooth version 4.0 is known as Bluetooth Low Energy or BLE, which remains in sleep mode constantly except for when a connection is initiated.

Bluetooth Classic

On this project I will show you how to communicate with Bluetooth Classic by typing message and to switch on the LED via application.

Parts and components

  • ESP32 Board
  • Breadboard
  • Male to male jumper wires
  • 330 Ohm resistor
  • LED
  • Arduino IDE
  • USB Cable
  • Serial Bluetooth Terminal App

Serial to serial communication

First, I prepared the parts, components, and software needed. I installed Serial Bluetooth Terminal App on my mobile phone. Then, I connected the ESP32 to a laptop using USB cable. After uploading the code below, opened the serial monitor at 115200 baud rate and I pressed “EN” (Enable) button.

This code is from File > Examples > BluetoothSerial > SerialtoSerialBT.

File > Examples > BluetoothSerial > SerialtoSerialBT
//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);
}

I turned on the bluetooth on my phone and opened the app. Then, I paired the devices by clicking “Devices”. After that, I tried to type and send a message to the serial monitor and this was shown.

Hello

That means the bluetooth worked! Let’s jump to the next trial.

Turn on the LED

I want to turn on the LED by clicking the button in the Serial Monitor App. After turning on/off the LED, the LED status will be shown on serial monitor (‘LED is on’ or ‘LED is off’).

Schematics
/*********
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;
const int ledPin = 5;
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);
SerialBT.println("LED is on");
}
else if (message =="led_off"){
digitalWrite(ledPin, LOW);
SerialBT.println("LED is off");
}
delay(20);
}
Turn on — turn off

Bluetooth Low Energy

Bluetooth Low Energy (BLE) is a power-conserving Bluetooth for short distance transmission of small data. BLE remains in sleep mode except for when a connection is initiated so it can consume less power.

Source is from randomnerdtutorials.

Parts and Components

  • ESP32 Board
  • Breadboard
  • nRF Connect for Mobile
  • USB Cable

ESP32 BLE Server

Open Arduino and go to File > Examples > ESP32 BLE Arduino > BLE_server. This code below will be shown. Verify and upload.

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

ESP32 BLE Scan

Open Arduino and go to File > Examples > ESP32 BLE Arduino > BLE_scan. This code below will be shown. Verify and upload.

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

Verify and upload. Then open the serial monitor at 115200 baud rate. Don’t forget to press ‘EN’ (enable), and this will show.

Devices found = 1

Testing with Smartphone

To try this project, download nRF Connect for Mobile on Play Store (Android) or App Store (iOS).

I downloaded the app and tried to scan nearby ESP32 device but no devices found. I checked the serial monitor and devices found turned to 0. I don’t know what happened but it changed :)

Final say

Sadly for now I can’t connect to the ESP32. Will try later and find out what was wrong :)

--

--