ESP32 BLE Advertiser (Pairs with Python Scanner)
ESP32 BLE Advertiser (Pairs with Python Scanner)
animation
bluetooth-ble
python
NoteTry It: ESP32 BLE Advertiser (Pairs with Python Scanner)
Objective: Run an ESP32 as a BLE peripheral that advertises a custom service. In a real setup, you would connect to this device using the Python bleak scanner code above.
Open the simulator directly: Wokwi ESP32 starter project.
Code to Try:
#include <BLEDevice.h>
#include <BLEServer.h>
#define SERVICE_UUID "181A0000-0000-1000-8000-00805f9b34fb"
#define TEMP_CHAR_UUID "2A6E0000-0000-1000-8000-00805f9b34fb"
#define HUMIDITY_CHAR_UUID "2A6F0000-0000-1000-8000-00805f9b34fb"
BLECharacteristic *pTempChar, *pHumChar;
bool deviceConnected = false;
class CB : public BLEServerCallbacks {
void onConnect(BLEServer* s) { deviceConnected = true; }
void onDisconnect(BLEServer* s) {
deviceConnected = false;
BLEDevice::startAdvertising();
}
};
void setup() {
Serial.begin(115200);
BLEDevice::init("ESP32-EnvSensor");
BLEServer* srv = BLEDevice::createServer();
srv->setCallbacks(new CB());
BLEService* svc = srv->createService(SERVICE_UUID);
pTempChar = svc->createCharacteristic(TEMP_CHAR_UUID,
BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
pHumChar = svc->createCharacteristic(HUMIDITY_CHAR_UUID,
BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
svc->start();
BLEDevice::getAdvertising()->addServiceUUID(SERVICE_UUID);
BLEDevice::startAdvertising();
}
void loop() {
float temp = 22.0 + random(-30, 30) / 10.0;
float hum = 55.0 + random(-100, 100) / 10.0;
int16_t tBLE = (int16_t)(temp * 100); // 0.01 C units
uint16_t hBLE = (uint16_t)(hum * 100);
pTempChar->setValue((uint8_t*)&tBLE, 2);
pHumChar->setValue((uint8_t*)&hBLE, 2);
if (deviceConnected) { pTempChar->notify(); pHumChar->notify(); }
delay(2000);
}What to Observe:
- The ESP32 advertises as “ESP32-EnvSensor” with a custom Environmental Sensing service
- Temperature and humidity values are encoded as BLE-standard int16 in 0.01-degree units
- When a client connects, notifications push data automatically every 2 seconds
- Try changing the device name in
BLEDevice::init()and observe how it affects discovery