用ArduinoBLE函数库写蓝牙传输信息的代码
时间: 2024-04-29 14:25:02 浏览: 76
FANUC_focas函数库(中文版)
5星 · 资源好评率100%
下面是一个简单的使用ArduinoBLE函数库的蓝牙传输信息的代码:
```
#include <ArduinoBLE.h>
BLEService service("6E400001-B5A3-F393-E0A9-E50E24DCCA9E");
BLECharacteristic txCharacteristic("6E400002-B5A3-F393-E0A9-E50E24DCCA9E", BLERead | BLENotify, 20);
BLECharacteristic rxCharacteristic("6E400003-B5A3-F393-E0A9-E50E24DCCA9E", BLEWrite, 20);
void setup() {
Serial.begin(9600);
if (!BLE.begin()) {
Serial.println("Starting BLE failed!");
while (1);
}
BLE.setLocalName("Arduino BLE");
BLE.setAdvertisedService(service);
service.addCharacteristic(txCharacteristic);
service.addCharacteristic(rxCharacteristic);
BLE.addService(service);
rxCharacteristic.setCallbacks(new MyRXCallback());
BLE.advertise();
Serial.println("Waiting for connections...");
}
void loop() {
// do nothing
delay(1000);
}
class MyRXCallback : public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *rxCharacteristic) {
std::string value = rxCharacteristic->getValue();
Serial.println(value.c_str());
txCharacteristic.setValue(value);
txCharacteristic.notify();
}
};
```
请注意,此代码仅用于演示目的,实际使用时应该添加错误检查和处理代码以保护程序免受攻击。
阅读全文