2025年5月25日日曜日

BLE5-esp32(sunfounder::1,23....) receiver

bleセンダー:: https://docs.sunfounder.com/projects/

esp32-starter- kit/ja/latest/arduino/basic_projects/ar_bluetooth.htmlで

arduinoIDE serial monitor と読み書きに成功した ただしサイトにある以下のくだり

「Receive UUIDをクリックします。右の Data Format ボックスで適切なデータフォーマットを選択します。例えば、「HEX」を16進数、「UTF-8 String」を文字、「Binary」を2進数などに設定します。その後、 SUBSCRIBE をクリックします。」

はmy Light Blueではdata formatボックスはなく、read/writeのそれぞれのuuidをtapして

でてくる冒頭のCharacteristicの横にhexとあるので都度utf8にsaveし直しが必要

(理由は不明だが、頻繁にhexにもどってしまう。。。。要注意!

なお、手持ちのesp32(akiz/china)のbleは5なのでbluetooth serial terminalはつかえない

逆にpicow,microbitは古いble4なのでbluetooth serial terminalしかつかえない

ble-trial-32.ino::

#include "BLEDevice.h"

#include "BLEServer.h"

#include "BLEUtils.h"

#include "BLE2902.h"


// Define the Bluetooth device name

const char *bleName = "ESP32_Bluetooth";


// Define the received text and the time of the last message

String receivedText = "";

unsigned long lastMessageTime = 0;


// Define the UUIDs of the service and characteristics

#define SERVICE_UUID           "eaf73a5b-f0e6-4316-8d9c-a04cbfc361d5"

#define CHARACTERISTIC_UUID_RX "7d9b4a42-b4c6-4887-b3a3-83e1c87fd6ae"

#define CHARACTERISTIC_UUID_TX "0ccd4f77-ace5-4456-a79f-e376f1c96339"


// Define the Bluetooth characteristic

BLECharacteristic *pCharacteristic;


void setup() {

  Serial.begin(115200);  // Initialize the serial port

  setupBLE();            // Initialize the Bluetooth BLE

}


void loop() {

  // When the received text is not empty and the time since the last message is over 1 second

  // Send a notification and print the received text

  if (receivedText.length() > 0 && millis() - lastMessageTime > 1000) {

    Serial.print("Received message: ");

    Serial.println(receivedText);

    pCharacteristic->setValue(receivedText.c_str());

    pCharacteristic->notify();

    receivedText = "";

  }


  // Read data from the serial port and send it to BLE characteristic

  if (Serial.available() > 0) {

    String str = Serial.readStringUntil('\n');

    const char *newValue = str.c_str();

    pCharacteristic->setValue(newValue);

    pCharacteristic->notify();

  }

}


// Define the BLE server callbacks

class MyServerCallbacks : public BLEServerCallbacks {

    // Print the connection message when a client is connected

    void onConnect(BLEServer *pServer) {

      Serial.println("Connected");

    }

    // Print the disconnection message when a client is disconnected

    void onDisconnect(BLEServer *pServer) {

      Serial.println("Disconnected");

    }

};


// Define the BLE characteristic callbacks

class MyCharacteristicCallbacks : public BLECharacteristicCallbacks {

    void onWrite(BLECharacteristic *pCharacteristic) {

      // When data is received, get the data and save it to receivedText, and record the time

      std::string value = std::string(pCharacteristic->getValue().c_str());

      receivedText = String(value.c_str());

      lastMessageTime = millis();

      Serial.print("Received: ");

      Serial.println(receivedText);

    }

};


// Initialize the Bluetooth BLE

void setupBLE() {

  BLEDevice::init(bleName);                        // Initialize the BLE device

  BLEServer *pServer = BLEDevice::createServer();  // Create the BLE server

  // Print the error message if the BLE server creation fails

  if (pServer == nullptr) {

    Serial.println("Error creating BLE server");

    return;

  }

  pServer->setCallbacks(new MyServerCallbacks());  // Set the BLE server callbacks


  // Create the BLE service

  BLEService *pService = pServer->createService(SERVICE_UUID);

  // Print the error message if the BLE service creation fails

  if (pService == nullptr) {

    Serial.println("Error creating BLE service");

    return;

  }

  // Create the BLE characteristic for sending notifications

  pCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_TX, BLECharacteristic::PROPERTY_NOTIFY);

  pCharacteristic->addDescriptor(new BLE2902());  // Add the descriptor

  // Create the BLE characteristic for receiving data

  BLECharacteristic *pCharacteristicRX = pService->createCharacteristic(CHARACTERISTIC_UUID_RX, BLECharacteristic::PROPERTY_WRITE);

  pCharacteristicRX->setCallbacks(new MyCharacteristicCallbacks());  // Set the BLE characteristic callbacks

  pService->start();                                                 // Start the BLE service

  pServer->getAdvertising()->start();                                // Start advertising

  Serial.println("Waiting for a client connection...");              // Wait for a client connection

}

0 件のコメント:

コメントを投稿