ESP32 BLE Client: Connect, Scan and Pair Example
In the realm of Internet of Things (IoT) development, the ESP32, with its massive community and endless capabilities, stands out as a popular choice. One of its compelling features is its support for Bluetooth Low Energy (BLE), enabling ESP32 to communicate with other BLE devices seamlessly. This article explores a practical example of setting up an ESP32 as a BLE client, communicating with a BLE server to control a simple LED.
Before diving into the example, ensure you have the following: an ESP32 development board, a USB-to-serial converter or a USB cable, and an Arduino IDE configured for ESP32 boards, along with the necessary BLE libraries.
Setting Up the ESP32 Board
The first step involves preparing the ESP32 board by installing the necessary firmware and connecting it to your computer.
1. Open the Arduino IDE and go to Tools > Board and select your ESP32 board. Then, select the correct COM port under Tools > Port.
Installing the BLE Library
The ESP32 requires the BLE Primer Library to function as a BLE client. You can install it via the Library Manager in the Arduino IDE as follows:
1. Go to Sketch > Include Library > Manage Libraries. Search for "BLE Primer" and install it.
Connecting to the BLE Server
Once the library is installed, we'll use it to connect the ESP32 to a BLE server, like a smartphone app, that acts as a central device. We'll be using a simple LED for this example, which the server will control.
1. Write an Arduino sketch on your ESP32 board that initializes the BLE client, scans for the server, and connects to it.
2. Upon connecting, the ESP32 should read the BLE characteristic (a specific value sent by the server) and control the LED accordingly. Here's a simple sketch to get you started:
```cpp #includeUpload this sketch to your ESP32 board, and once it's connected to the BLE server, the built-in LED should turn on or off based on the server's instructions.
Testing the BLE Client
To test the ESP32 BLE client, you can use a BLE server app on your smartphone. There are various apps available, like "LightBlue" for iOS or "nRF Connect" for Android, that allow you to create and control BLE services.
1. Create a new service in the app and add a characteristic named "LED" with an integer data type. Set the initial value to 0.
2. Start the advertising process in the app, then open the Arduino IDE running the ESP32 sketch. The ESP32 should connect to the app and control the LED accordingly.
With this example, you have now created a simple ESP32 BLE client capable of communicating with a BLE server. You can build upon this foundation to create more complex IoT devices, integrating various sensors and actuators. Happy tinkering!