这是场景。 Arduino A连接了按钮A。按下按钮A时,LED A点亮,LED B熄灭。再次单击时,LED A熄灭,LED B点亮。我将其与其他方面完全放在控制和工作之中。我要完成的下一步是将BLE Notify纳入arduino。当单击按钮并打开LED A时,我希望BLE通知发送一些东西(例如'G')。然后,如果再次按下该按钮,则BLE通知将发送不同的内容(“ R”)。
我尝试将'BLE_Notify'Sketch示例结合到我的代码中,但是当我将Arduino连接到BLE电话应用程序时,我无休止地收到了无数次的更改通知。下面是我的组合代码。
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
BLEServer* pServer = NULL;
BLECharacteristic* pCharacteristic = NULL;
bool deviceConnected = false;
bool oldDeviceConnected = false;
uint32_t value = 0;
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
deviceConnected = true;
};
void onDisconnect(BLEServer* pServer) {
deviceConnected = false;
}
};
const int bt1 = 27;
boolean bt1g = true;
int bt1t = 0;
void setup() {
pinMode(33, OUTPUT);
pinMode(15, OUTPUT);
pinMode(bt1, INPUT_PULLUP);
Serial.begin(9600);
BLEDevice::init("ESP32");
pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
BLEService *pService = pServer->createService(SERVICE_UUID);
pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE |
BLECharacteristic::PROPERTY_NOTIFY |
BLECharacteristic::PROPERTY_INDICATE
);
pCharacteristic->addDescriptor(new BLE2902());
pService->start();
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(false);
pAdvertising->setMinPreferred(0x0);
BLEDevice::startAdvertising();
Serial.println("Waiting a client connection to notify...");
}
void loop()
{
if (deviceConnected) {
pCharacteristic->setValue((uint8_t*)&value, 4);
pCharacteristic->notify();
value++;
delay(3); /
}
if (!deviceConnected && oldDeviceConnected) {
delay(500);
pServer->startAdvertising();
Serial.println("start advertising");
oldDeviceConnected = deviceConnected;
}
if (deviceConnected && !oldDeviceConnected) {
oldDeviceConnected = deviceConnected;
}
if (bt1g) {
if (digitalRead(bt1) == LOW ) {
bt1t = (bt1t + 1) % 2;
Serial.println(bt1t);
bt1g = false;
}
}
if (!bt1g) {
if (digitalRead(bt1) == HIGH) {
bt1g = true;
}
}
if (bt1t == 0) {
digitalWrite(33, LOW);
digitalWrite(15, HIGH);
pCharacteristic->setValue(0);
pCharacteristic->notify();
value++;
}
if (bt1t == 1) {
digitalWrite(33, HIGH);
digitalWrite(15, LOW);
pCharacteristic->setValue(1);
pCharacteristic->notify();
value++;
}
delay(50);
}
我对Arduino和C ++环境非常陌生,如果我的代码不正确,请对不起。