ESP32C3 BLE Bluetooth Low Energy Communication Example

ESP32C3 BLE Bluetooth Low Energy Communication Example

This example includes host and slave code. The slave broadcasts a message, then goes into a deep sleep for 1 second and repeats the process. The host receives the message. This allows the slave to achieve very low power consumption. The host can receive broadcast messages from multiple slaves.

ESP32C3 is available here.

Host:

#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
BLEScan* pScan;
class MyCallbacks : public BLEAdvertisedDeviceCallbacks {
    void onResult(BLEAdvertisedDevice device) {
        String data = device.getManufacturerData();
        if (data.length() == 4) {
            uint8_t* d = (uint8_t*)data.c_str();
            uint8_t id = d[0];
            uint8_t temp = d[1];
            uint8_t hum = d[2];
            uint8_t status = d[3];
            //Serial.printf("Device %d -> T=%d H=%d S=%d\n",
            //              id, temp, hum, status);
            Serial.printf("Device %d -> count=%d\n",
                          id, temp);
        }
    }
};
void setup() {
    Serial.begin(115200);
    BLEDevice::init("");
    pScan = BLEDevice::getScan();
    pScan->setAdvertisedDeviceCallbacks(new MyCallbacks());
    pScan->setActiveScan(true);
    Serial.println("Scanning...");
}
void loop() {
    pScan->start(1, false);
    //delay(1000);
}
 
Slave:
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEAdvertising.h>
#include "esp_sleep.h"
BLEAdvertising* pAdvertising;
uint8_t device_id = 2;
void setup() {
    Serial.begin(115200);
 
    esp_sleep_wakeup_cause_t wakeup_reason = esp_sleep_get_wakeup_cause();
    Serial.printf("Wakeup reason: %d\n", wakeup_reason);
 
    BLEDevice::init("ESP32C3-SLAVE");
    pAdvertising = BLEDevice::getAdvertising();
    pAdvertising->setScanResponse(false);
 
    static uint8_t count = 0;
    uint8_t temp = random(20, 30);
    uint8_t hum  = random(40, 70);
    uint8_t status = 1;
    uint8_t payload[4];
    payload[0] = device_id;
    payload[1] = count++;
    payload[2] = hum;
    payload[3] = status;
    BLEAdvertisementData advData;
    String strPayload = String((char*)payload, 4);
    advData.setManufacturerData(strPayload);
    pAdvertising->setAdvertisementData(advData);
 
    pAdvertising->setMinInterval(160);  // 100ms
    pAdvertising->setMaxInterval(160);
 
    pAdvertising->start();
    Serial.printf("Broadcast: ID=%d T=%d H=%d\n",
                  device_id, temp, hum);
 
    delay(200);   // ⭐ important:resert some time to be received
    pAdvertising->stop();
    Serial.println("Going to deep sleep...");
    esp_sleep_enable_timer_wakeup(1000000); // 1second = 1000000us
    esp_deep_sleep_start();
}
void loop() {
}