Contact Us
Blog / ESP32 BLE(Bluetooth Low Energy) Control in Arduino IDE

ESP32 BLE(Bluetooth Low Energy) Control in Arduino IDE

Posted:02:57 PM November 17, 2023 writer: The Engineering Projects

Hi learners! I hope you are doing great. Welcome to the next episode of ESP32 training, where we are moving towards the ESP32 Bluetooth low energy (BLE) and will see a practical example at Arduino IDE. In the previous session, along with all the basic concepts, I discussed the basics of ESP32 in the Arduino IDE and mentioned the introduction of ESP32 BLE mode. Today, we will see the practical implementation of the ESP32 BLE functionality as a server. We know the ESP32 microcontroller board works like the Arduino but the major difference between these two is that the ESP32 has BLE and WiFi functionalities. Therefore, we are discussing the ESP32 BLE in detail.

In this article, we will start with the basic introduction of Bluetooth low energy. After that, we will see the key features of this module. We will compare the BLE with classic Bluetooth and use the tables for quick revision. After that, we will go through some important concepts that will help us in the practical example. We will create our own server and download the BLE scanner app to use as a client. In the end, we will see how the built-in examples of the Arduino IDE help us create different programs related to ESP32 BLE. Let us move towards the first section. 

Introduction to Bluetooth Low Energy

Bluetooth Low Energy (BLE) is a wireless communication technology that is designed for low-power applications. Hence, it is a power-conservative variant of Bluetooth that is designed for the transmission of small amounts of data among devices. This wireless personal area network technology is a popular choice for small and portable devices such as smart home appliances, smartphones, wearables, and many IoT (Internet of Things) devices. In such projects, Bluetooth low energy plays the basic role of connecting the devices wirelessly.

Key Features of Bluetooth Low Energy

The BLE is designed in a specialized manner because it targets a wide range of devices. Here are some basic features of this technology that every user must know:

Low Power Consumption

The basic feature of this technology is its low power consumption, which makes it ideal for a large range of wearable and portable devices. It uses short data packages and low-duty cycles, making it ideal for battery-operated devices. In this way, the BLE-operated devices can get power for a long time, even with small coin batteries.

Power States of BLE

There are two basic types of power states for Bluetooth low-energy. These devices are designed to provide versatility; therefore, these modes help to maintain the ideal functionality with the least power consumption:

  • In active mode, the device with BLE consumes full power and is active for data receiving and transmission. It can perform functions such as scanning other devices, making connections and exchanging data between the devices. In this mode, more power is used as compared to the sleep mode. 
  • The sleep state of the BLE allows for fewer functionalities because the device is partially or fully powered off. It does not scan for new connections and does not exchange data between the connected devices. This mode is ideal for devices that do not work all the time but have to be turned on only when required. There are different types of sleep modes in BLE, such as:
    • Idle Mode
    • Connection Event Sleep Mode
    • Periodic Advertising Mode
    • Deep Sleep Mode

 

Get Instant Online Quote

The average power consumption of the devices for BLE is usually 10 mA in active mode and less than 5 µA in sleep mode. The following table will show the summary of each mode:

 

Mode

Description

Power Consumption

Responsiveness

Active Mode

  • The device is fully powered up
  • Ready to transmit and receive data 
  • Actively scans for other devices
  • Maintains connections
  • Exchanges data

High

High

Sleep Mode

  • The device is partially or fully powered down
  • May not be actively scanning for other devices
  • May not maintain connections  
  • Usually, takes longer to respond to communication requests

Low

Low

Idle Mode

  • The device is still partially active
  • Can respond to communication requests within a few milliseconds.

Medium

Medium

Connection Event Sleep Mode

  • The device is only active during scheduled connection events to exchange data with the central device. 
  • Saves power by sleeping between connection events.

Medium

Low

Periodic Advertising Mode

  • The device periodically wakes up to advertise its presence and can be discovered by central devices.
  • Remains in sleep mode most of the time
  • Minimized power consumption.

Low

Medium

Deep Sleep Mode

  • The device is completely powered down
  • Cannot respond to communication requests until it wakes up from sleep
  • Consumes the least amount of power but requires the longest wake-up time.

Very Low

Very Low


Connection Range of Working 

The BLE works on the short range of the device, which means it is not able to connect devices placed at a long distance. This range varies according to environmental factors. 

Usually, the devices can be connected to each other within a range of 100 meters in an open area. The range of BLE devices in the closed rooms and areas is less than these because the wall acts like a hurdle in signal transmission. 

Low Cost and Low Latency

The BLE module has a low cost and provides functionalities that are suitable for a large range of projects; therefore, it is considered one of the most affordable modules for wearables and other IoT devices. 

On the other hand, it shows the low latency communication that enables the device to be a quick and responsive device with low power. It is an important feature because this module is usually used in wearable devices and IoT projects that require a quick response at the right time. 

Security Features of BLE

The BLE provides secure transmission of data among the devices; therefore, it is the main feature of multiple devices. It has the built-in features of encryption and authentication and can protect the data to ensure the privacy of the user. The good thing about this module is that it provides a secure connection and data exchange.

GATT Profile in Bluetooth 

The BLE uses the GATT profile to simplify the services, characteristics, and attributes. You will see the details about it in the coming section. Through GATT, the BLE can be designed according to the user's requirements, and this provides versatility and variation in the features. 

Bluetooth Mesh 

The Bluetooth Low Energy supports the mesh system for the networking of the devices. Therefore, the devices can form self-healing and large-scale networks. This is important in projects like smart lighting, smart buildings, and other types of IoT networks.  

Low Complexity and IoT Devices

The BLE is suitable for a broad spectrum of use cases; therefore, it can support projects ranging from simple, low complexity to highly sophisticated applications. This makes it an ideal choice for IoT projects (as mentioned earlier). This module can be used to connect a wide range of sensors together that can be controlled with the help of a central device, such as a smartphone. 

Comparison of BLE and Classic Bluetooth

There are two types of Bluetooth in the ESP32 (as mentioned in the previous session) Bluetooth Low Energy (BLE) and Bluetooth Classic. Both of these are developed by the Bluetooth Special Interest Group (SIG) and are wireless technologies for the transmission of data among devices. However, these have different characteristics that make them suitable for different types of devices. It is better to understand the workings and features of BLE by comparing it with classic Bluetooth. Classic Bluetooth is an older technology; therefore, I will discuss its functionality first and then BLE so the reader may know what’s new in the Bluetooth technology. Here is the comparison between these:

Power Consumption

The power consumption of classic Bluetooth is higher than that of BLE. This is the main difference between these two. It is suitable for applications such as audio streaming where a continuous power source is attached. It consumes around 30-50 mA in its active mode and 10 mA in standby mode.

On the other hand, BLE is designed to work with battery-oriented devices; therefore, it consumes low power. It has a power consumption of less than 10 mA in its active mode and even less than 5 µA in sleep mode.

Range of Bluetooth

The Bluetooth Classic has a longer range as compared to the BLE, depending on the type of Bluetooth Classic (class 1, class 2, class 3). Typically, it can share the data at a distance of up to 100 meters in open environments and up to 10 meters indoors. The range of BLE is usually less than this. 

Complexity

The complexity of Bluetooth Classic is more complex than that of BLE. It is designed for more powerful devices; therefore, it has a complex protocol stack. On the other hand, BLE is well-suited for resource-constrained devices and has a simple protocol stack. 

Bluetooth Mesh

The Classic Bluetooth does not have the feature of Bluetooth mesh; therefore, it can not create a large cell network of devices, which is an important feature of BLE.

 

Feature

Bluetooth Low Energy (BLE)

Classic Bluetooth

Power Consumption

Low

Moderate to High

Range

Short (up to 100 meters)

Moderate to Long

Data Rate

Low to Moderate (up to 2 Mbps)

Moderate to High

Connection and Discovery

  • Quick connection
  • Efficient data exchange 
  • Easy device discovery
  • Slightly longer connection times 
  • More complex pairing and discovery

Interoperability

Designed for interoperability

Promotes interoperability

Complexity

Relatively simple protocol stack, suitable for resource-constrained devices

More complex protocol stack, suitable for more powerful devices

Audio Streaming

Not ideal for high-quality audio streaming

Specifically designed for high-quality audio streaming

Bluetooth Mesh

Supports Bluetooth Mesh networking

Does not support mesh networking

Beacon Technology

Commonly used for beacon applications

Not commonly used for beacon applications

Security

Supports encryption and authentication

Supports encryption and authentication

Cost

Generally lower cost

Generally higher cost

Battery Life

Longer due to low power consumption

Shorter due to higher power consumption

Usability

Easier to use due to the simpler protocol stack

More complex to use due to the more complex protocol stack

Applications

  • Wearables
  • Smart home devices
  • Beacons
  • Medical devices
  • IoT sensors
  • Audio headsets
  • Wireless speakers
  • Car hands-free kits
  • Data transfer between devices

 

Get Instant Online Quote

Basic Concepts in BLE Connection with ESP32

There are some concepts that must be clear before using the BLE for the transmission of data. Here are the basics of BLE:

Server and Client

  • Communication between devices requires at least two types of devices, server and client. 
  • The server advertises the presence of ESP32 to the client so that it may connect and transfer the data. 
  • This presence is shown when the Bluetooth option of the client is opened and the server name appears on the screen. 
  • The client scans for nearby devices ready to pair with it. Once the connection is stable, it can listen to and read the data from the server.
  • The whole scenario is called point-to-point communication. 

Communication Modes of BLE

BLE supports two types of communication modes:

  1. In broadcast mode, the server can send the data to all the devices connected to it. This is the basic working of Bluetooth. 
  2. The second mode is called mesh mode because, in it, the network of the server and connected devices can communicate within the whole network. It means the server can send the data to a device and devices can also send the data to other devices. 

As mentioned before, the mesh mode is the advantage of using the BLE over the Classic Bluetooth. This has made the BLE versatile and provided a wide range of project options. 

 

GATT in BLE

Generic attribute (GATT) is the data structure that defines the way in which two BLE devices can send and receive the data. Through this, the user can set up the connection according to the project. The following hierarchy is important to understand in order to establish the connection between BLE devices. 

Profile in GATT

  • The profile in BLE is essential because it ensures that the devices in the BLE network are incorporating and communicating according to the use case. 
  • These provide a standardized way to exchange the data. 
  • Usually, the profile consists of service and characteristics. 

Service in GATT

  • A service is a collection of different characteristics. It defines the functionality or features of the BLE device. 
  • It is the collection of data from the device. For instance, in the case of the ESP32, it may be the data coming from sensors. 
  • The BLE supports multiple devices and collectively, the services of all these devices create the profile. 

Characteristics in GATT

  • These characteristics are always present in the services. 
  • The actual data is present in the characteristic in the hierarchical format. 
  • The characteristic has two attributes:
    • Characteristic declaration: Provides metadata about the data
    • Characteristic value: The actual value of the data
  • Each characteristic has its own specific UUID (you will learn about it in the next section).

Properties of Characteristics in BLE

  • The properties define the behavior and capabilities of the characteristics.
  • These decide how to access and use the characteristics. 
  • The most common examples of properties are given next:
    • Read (PROPERTY_READ)
    • Write (PROPERTY_WRITE)
    • Notify (PROPERTY_NOTIFY)

Descriptor in BLE GATT

  • Descriptors are the metadata of the characteristics.
  • These provide additional information and descriptions. 
  • The configuration options for characteristics are defined in the descriptors.

UUID in Bluetooth Low Energy

  • The universal unique identifier (UUID) is the unique 128-bit (16-byte) number in BLE.
  • With the help of UUID, profiles, data types, etc. are identified. 
  • The Bluetooth Special Interest Group specifies the shortened UUIDs for types, services, and profiles.
  • Different UUID generators are available online if the user wants to create their own UUIDs at the following link:
      https://www.uuidgenerator.net/

ESP32 BLE on Arduino IDE

The ESP32 is a microcontroller that can be used either as a client or server. In the previous session, Getting Started with ESP32, we made changes to the default settings of the Arduino IDE to make it compatible with the ESP32. We installed the board, port, and libraries for ESP32. Now, we are going to set the ESP as a server and for this, we have to make some other changes. Follow the steps given next to use ESP32 as a server using the Arduino IDE.

Arduino IDE for ESP32 as Server

  • Fire up your Arduino IDE. 
  • Go to the File>new sketch to create the sketch for this project. 
  • If your board is not selected, go to Tools>Boards>ESP32>Node32s.
  • If you are using any other port, go to Tools>Port>Com4. This port number may vary on your device. 

ESP32 Bluetooth Library Installation

  • Go to Sketch>Include Libraries>Manage Libraries. It will open a search bar on one side of your screen. 
  • Type BLE_HID and search for the Mbed BLE HID.
  • Click the install button and it will show the loading process in the console window.



 

  • Once the loading stops, the “Install” button is changed to "Remove”. It indicates that the library is installed successfully. 

Installation of Android App for BLE

There are different ways to perform this experiment. As said earlier, the ESP32 can act either as a server or as a client. In this experiment, we will use the app to carry on the communication. This is an easier method and usually, students prefer to control the Bluetooth through a proper interface. 

Once the Arduino IDE is ready, the user has to install the mobile app to create the connection between mobile/iPhone and ESP32. In this way, the ESP32 will act as a server and the mobile app will be the client. Follow the steps to get the app:

 

  • Go to the Playstore/Apple app store of your Android phone/Apple iOS.
  • Search the BLE scanner (Connect and Notify) there. 

 

  • Once you get it, download the app, and it will automatically install it. 

Using the BLE Scanner as a Client

  • Now, when the app is installed, click on the icon to start it. 
  • The splash screen will show the interfaces of the app. 
  • It will ask for some permissions, such as the location of the user.
  • Provide the permissions and the app is ready to use. 

 

Code for Testing ESP32 as a Server 

  • Go to the Arduino IDE to create the code. 
  • Now, copy the following code and paste it on the ESP32 sketch:

#include

#include

#include

#include

 

int ledPin = 2;  // GPIO pin connected to the built-in LED on the ESP32

 

class MyServerCallbacks : public BLEServerCallbacks {

  void onConnect(BLEServer* pServer) {

    // Device connected

  }

 

  void onDisconnect(BLEServer* pServer) {

    // Device disconnected

  }

};

 

BLEServer* pServer = NULL;

BLECharacteristic* pCharacteristic = NULL;

 

#define SERVICE_UUID "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"

#define CHARACTERISTIC_UUID "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"

 

void setup() {

  Serial.begin(115200);

  pinMode(ledPin, OUTPUT);  // Set the LED pin as an output

  digitalWrite(ledPin, LOW);  // Turn off the LED initially

 

  BLEDevice::init("ESP32 BLE as Server");

  pServer = BLEDevice::createServer();

  pServer->setCallbacks(new MyServerCallbacks());

  BLEService* pService = pServer->createService(SERVICE_UUID);

  pCharacteristic = pService->createCharacteristic(

    CHARACTERISTIC_UUID,

    BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE

  );

  pCharacteristic->setValue("Hello from ESP32 Server TEP");

  pService->start();

  pServer->getAdvertising()->start();

}

 

void loop() {

  // The main code can run here

}

 

void toggleLED() {

  digitalWrite(ledPin, HIGH);  // Turn on the LED

  delay(500);  // Delay for half a second

  digitalWrite(ledPin, LOW);  // Turn off the LED

}

 

  • Click on the “Verfiy” button to check for errors.
  • Once the loading is complete without errors, click on the “Upload” button. 
  • Check the app; if all goes well, the app will show the name of the device as “ESP32 BLE as Server” on the screen. 

  • Click on the connect button. 
  • The following screen will show the details of the connection. 

 

ESP32 BLE Server Program Results

  • The window will show different options that show the details of the connection. 
  • Click on the Custom server window, it will show the option to read and write from the ESP32.



 

  • Click on the “R” button to read the message from ESP32. It will show “Hello from ESP32 Server” as we have written in the code. 



 

 

You can see the message “Hello from the ESP32 Server” on the screen. This message can be changed by the user through code. 

Get Instant Online Quote

Built-in ESP32 BLE Example

  • There are built-in examples that can be accessed for easy installation. 
  • Go to the File>Examples>ESP BLE Arduino and click on any example.

  •  A new window will be opened with the program. Read the program; it has some information about the creator of the code. You will see a string message with the same name. 
  • Verify the code through Arduino. If any code is saved in the ESP32 (such as mine because I have performed the previous example) click on the reset button and then verify the code. 
  • Hold the boot button on the ESP32 and click “Upload” on the Arduino IDE. 






 

This time, the Name of the device is “Long name works now” as mentioned in the built-in examples. Click on it. 

  • The read operation gives us the string “Hello World says Neil”. 

 

Hence, we have read a lot about the ESP32 in this tutorial. In the previous session, we read the basics and today, we have seen the concept of Bluetooth Low Energy in the ESP32. The ESP32 has two modes, Bluetooth and BLE, which have the latest features, such as being more effective, less power consumer, and low latency module. We have compared it with the Classic Bluetooth and read about the concepts, such as GATT, UUID, and other characteristics of BLE. In the end, we saw the ESP32 BLE in Arduino IDE. We implemented an example to do so and used the BLE Scanner app for this. In the end, we saw how the built-in examples of Arduino IDE can perform the tasks. I hope it was a helpful tutorial for you but still, if you are stuck at any point, you can ask in the comment section. 

You may also be interested in...

Getting Started with ESP32

Autumn Offer: Get $30 off PCB orders over $100 with NextPCB

Free PCB Assembly Offer is Now Live

HQ NextPCB Introduces New PCB Gerber Viewer: HQDFM Online Lite Edition

  • PCB
    Prototype
  • PCB
    Assembly
  • SMD
    Stencil

Dimensions: (mm)

×

Quantity: (pcs)

5
5
10
15
20
25
30
40
50
75
100
120
150
200
250
300
350
400
450
500
600
700
800
900
1000
1500
2000
2500
3000
3500
4000
4500
5000
5500
6000
6500
7000
7500
8000
9000
10000

Other Quantities:(quantity*length*width is greater than 10㎡)

OK

Layers:

Thickness:

Quote now