🛠 Être un périphérique Bluetooth LE avec ArduinoBLE

Arduino Nano ESP32 · intermediaire · Schéma : IMG-nano-esp32-intermediaire-2-nanoesp32-ble-arduino-ble.svg — Diffusion Bluetooth LE de la carte vers un smartphone exécutant nRF Connect.

Objectives

Make the Nano ESP32 a Bluetooth LE peripheral using the ArduinoBLE library: advertising a name, service, and a readable/notifiable characteristic incremented by the button. The NORA-W106 module handles multi-connection BLE 5.0 (central/peripheral).

Hardware

Complete code

#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>

BLECharacteristic* compteurChar = nullptr;
const uint8_t BTN = 2;
uint8_t n = 0;
uint32_t derniereMs = 0;

class ServeurCb : public BLEServerCallbacks {
  void onConnect(BLEServer* s) override { Serial.println("centrale connectée"); }
  void onDisconnect(BLEServer* s) override { BLEDevice::startAdvertising; }
};

void setup {
  Serial.begin(115200);
  pinMode(BTN, INPUT_PULLUP);
  BLEDevice::init("NanoESP32-Demo");
  BLEServer* serveur = BLEServer::createServer;
  serveur->setCallbacks(new ServeurCb);
  BLEService* service = serveur->createService("1280");
  compteurChar = service->createCharacteristic(
      "2A19", BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
  service->start;
  BLEAdvertising* adv = BLEDevice::getAdvertising;
  adv->addServiceUUID("1280");
  BLEDevice::startAdvertising;
  Serial.println("Diffusion BLE : NanoESP32-Demo");
}

void loop {
  bool appuye = (digitalRead(BTN) == LOW);
  uint32_t now = millis;
  if (appuye && now - derniereMs > 250 && compteurChar) {
    derniereMs = now;
    compteurChar->setValue(++n);
    compteurChar->notify;
    Serial.printf("compteur = %u\n", n);
  }
  delay(10);
}

Expected verification

nRF Connect displays “NanoESP32-Demo”; after connecting, the 2A19 characteristic value is 0 and then increments with each button press (after enabling notifications in the app).

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials