Creating Low-Power Bluetooth (BLE) with ESP32 Using Arduino IDE

In the ever-expanding universe of the Internet of Things (IoT), the ESP32 microcontroller has emerged as a true champion. Its compact form, dual-core processing capabilities, and built-in Wi-Fi have made it a cornerstone for IoT enthusiasts and professionals alike. However, what truly elevates the ESP32 to the forefront of IoT development is its seamless integration of Bluetooth Low Energy (BLE) technology. In this article, we embark on a journey to explore the technical nuances and diverse applications of ESP32 BLE. We’ll begin by understanding the essence of BLE, delve into the ESP32’s BLE features, and explore how it stands out from the crowd. Along the way, we’ll learn how to harness the power of this dynamic duo to create IoT solutions that shape our connected world.

Table of Contents

BLE & ESP32

What is it?

Bluetooth Low Energy

At its core, Bluetooth Low Energy (BLE) is a wireless communication technology designed for short-range data exchange. Unlike its predecessor, classic Bluetooth, BLE is optimized for low power consumption, making it an ideal choice for battery-powered devices and IoT applications. BLE operates in the 2.4 GHz ISM band and offers efficient communication with minimal energy usage. This makes it a perfect fit for IoT devices that need to transmit data while conserving battery life.

BLE devices are typically categorized into two roles: peripheral and central. A peripheral device, such as a sensor or wearable, advertises data to be discovered by central devices like smartphones or gateways. This client-server architecture of BLE allows for a wide range of IoT use cases, from monitoring environmental conditions to tracking assets and controlling smart appliances.

ESP32

The ESP32 microcontroller has been a game-changer in the world of IoT. With its dual-core CPU, Wi-Fi connectivity, and an array of GPIO pins, it has all the ingredients to power a variety of applications. However, what truly sets the ESP32 apart is its inbuilt BLE capability.

Combine Both

The ESP32 BLE stack is built on the ESP-IDF (Espressif IoT Development Framework) and supports BLE 4.0, 4.1, and 4.2. It can operate in both client and server roles, allowing it to connect to other BLE devices or act as a peripheral device itself. This flexibility opens the door to countless possibilities in the IoT ecosystem.

Getting started with ESP32 BLE development is relatively straightforward. You can choose from various development platforms, including the Arduino IDE and the ESP-IDF, depending on your level of expertise. Both platforms offer libraries and resources to simplify BLE development.

Creating a simple BLE server or peripheral application is a great way to begin your ESP32 BLE journey. You can program the ESP32 to advertise data that other BLE devices can discover and interact with. This approach is perfect for IoT scenarios where you want to collect data from sensors, such as temperature or humidity, and make it accessible to other devices.

Why Create ESP32 BLE Projects

When comparing the ESP32’s BLE capabilities to other popular BLE devices in the market, it’s important to highlight its strengths. The ESP32 stands out as a cost-effective and versatile choice. Its robust community support, extensive documentation, and compatibility with various development environments make it an attractive option for developers of all levels. While other BLE devices may excel in specific areas, the ESP32’s ability to combine BLE with Wi-Fi, powerful processing, and GPIO flexibility sets it apart as a well-rounded IoT enabler.

With support for Bluetooth Mesh, ESP32 enables the creation of expansive, self-healing networks that can encompass a multitude of interconnected devices, making it ideal for large-scale smart lighting, home automation, and industrial control applications. Leveraging the enhancements of Bluetooth 5.0, including an extended range of up to 200 meters and higher throughput, ESP32 facilitates efficient data exchange, enabling real-time audio streaming and swift firmware updates. Moreover, the ESP32’s ability to operate in both BLE and Classic Bluetooth modes concurrently offers developers unparalleled versatility, ensuring compatibility with a wide spectrum of Bluetooth devices, from smartphones to headsets, and paving the way for diverse and innovative IoT solutions.

Security is very important when discussing Bluetooth Low Energy because BLE technology is widely used in many modern applications, including smartphones, health devices, IoT devices, and more. ESP32 BLE can fully meet your security requirements:

  • Security Considerations: To safeguard data, developers should prioritize encryption, authentication, and privacy features. Encryption ensures that data exchanged between devices remains confidential. The ESP32 supports AES-CCM encryption, which secures the data payload and protects against eavesdropping.
  • Authentication: For secure connections, implement authentication mechanisms like passkeys or out-of-band (OOB) pairing. Passkeys are numerical codes exchanged between devices during pairing to confirm their identities. OOB pairing uses external methods, such as NFC, to establish a secure link between devices. The ESP32’s flexibility allows for the implementation of both methods to suit specific use cases.
  • Privacy Features: Privacy features like random address generation and address resolution protocol (ARP) mitigate tracking risks. Devices periodically change their BLE addresses, making it challenging for malicious actors to trace them. ARP allows devices to resolve each other’s addresses without exposing their actual identities.
  • Secure Data Transfer: To ensure secure data transfer, use secure channels, such as Secure Socket Layer (SSL) or Transport Layer Security (TLS). These protocols add an extra layer of encryption to protect data in transit. Additionally, implement secure key management practices to safeguard encryption keys.

ESP32 BLE Code

				
					#include <BLEUtils.h>
#include <BLE2902.h>
#include <BLEDevice.h>
// LED Pin
const int ledPin = 2; // Change this to the GPIO pin where your LED is connected
// RSSI Threshold (adjust as needed)
const int rssiThreshold = -60; // Set the RSSI threshold in dBm for proximity detection
// Callback when a BLE device is detected
class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks {
    void onResult(BLEAdvertisedDevice advertisedDevice) {
        int rssi = advertisedDevice.getRSSI(); // Get the RSSI value
        bool deviceFound = false; // Flag to indicate if a device is found during the scan
        // Check if the RSSI value is stronger than the threshold
        if (rssi >= rssiThreshold) {
            deviceFound = true;
            Serial.println("Found a nearby BLE device!");
            digitalWrite(ledPin, HIGH); // Turn on the LED when a nearby device is detected
            delay(1000); // Keep the LED on for 1 second (adjust as needed)
            digitalWrite(ledPin, LOW); // Turn off the LED
        }
        if (!deviceFound) {
            Serial.println("No device found.");
        }
    }
};
void setup() {
    Serial.begin(115200);
    pinMode(ledPin, OUTPUT);
    Serial.println("Waiting for a nearby Bluetooth device...");
    // Create and start the BLE server
    BLEDevice::init("");
    BLEScan* pBLEScan = BLEDevice::getScan();
    pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
    pBLEScan->setActiveScan(true);
    pBLEScan->start(5); // Scan for 5 seconds (adjust as needed)
    // Wait for the scan to complete (5 seconds in this case)
    delay(5000);
    // Stop the scan and clean up before starting the next scan
    pBLEScan->stop();
    BLEDevice::deinit();
    // Delay before starting the next scan (adjust as needed)
    delay(1000);
}
void loop() {
    // Your code here, if needed
}

				
			

This Arduino code is designed to detect nearby Bluetooth Low Energy devices and trigger an action, in this case, turning on an LED, when a nearby BLE device is found. 

The GPIO pin to which an LED is connected and an RSSI (Received Signal Strength Indicator) threshold value. It then sets up a callback function that gets called when a BLE device is detected. Inside this callback function, it checks the RSSI value of the detected device, and if it’s stronger (greater than or equal to the defined threshold), it prints a message indicating the presence of a nearby BLE device and turns on the LED for one second.

In the setup() function, it initializes the serial communication for debugging, configures the LED pin as an output, and prints an initial message. In the loop() function, it performs a BLE scan for a specified duration (5 seconds in this case). If it detects a nearby device during the scan, the device found flag is set to true. After the scan, it checks whether a device was found and then stops the scan, cleans up, and adds a delay before starting the next scan. This code can be used for various applications like proximity detection, tracking, or triggering actions based on the presence of specific BLE devices.

esp32 is not connected to ble
Not Connected
esp32 is connected to ble
Connected

ESP32 BLE in IoT Applications

The ESP32’s BLE capabilities find their true purpose in a myriad of IoT applications. Let’s explore a few real-world scenarios where ESP32 BLE plays a pivotal role:

  • Home Automation: Imagine controlling your smart lights, thermostats, and locks with your smartphone. ESP32 BLE can bridge the gap between your mobile device and smart home appliances, enabling seamless automation.
  • Health Monitoring: Wearable devices equipped with ESP32 BLE can continuously monitor vital signs, such as heart rate and oxygen levels, and transmit data to a central hub or healthcare provider.
  • Asset Tracking: In logistics and supply chain management, ESP32 BLE beacons can help track the location and condition of assets in real time, optimizing operations and reducing losses.
  • Wearable Technology: ESP32 BLE is the perfect companion for wearable devices. From fitness trackers to smartwatches, it enables efficient communication with smartphones and other peripherals.
  • Environmental Monitoring: Remote sensors equipped with ESP32 BLE can collect data on air quality, weather conditions, and more, transmitting valuable information for analysis and decision-making.
  • Proximity Detection: ESP32 BLE can be used to create proximity detection systems. For instance, it can trigger actions when a BLE device comes within a certain range, like opening doors or sending notifications.

More content you may be interested in

esp32 pinout
ESP32 Pinout Reference Guide

The ESP32 is a versatile microcontroller with extensive functionalities. Its pinout includes GPIO pins for digital, analog, and capacitive touch, PWM pins for precise control,

esp32 pwm project
ESP32 PWM Tutorial

This article delves into PWM on the ESP32, crucial for precise control in applications like LED dimming, motor regulation, and audio generation. It explains the

Scroll to Top