废话不多说下面是代码,这个代码的TX和RX是可以随意改的,但是接收的发送的方式只是提供一个思路,他发送和接收数据的效率不高,但是可以优化,解决思路就是顶一个数值和一个变量,每接收一个变量就加1,没有就退出然后发送变量大小的数据再清空数组,
#include <Arduino.h>
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
#include <stdint.h>
//uint8_t txValue = 0;
int contectok = 0;
BLEServer *pServer = NULL; //BLEServer指针 pServer
BLECharacteristic *pTxCharacteristic; //BLECharacteristic指针 pTxCharacteristic
bool deviceConnected = false; //本次连接状态
bool oldDeviceConnected = false; //上次连接状态
char BLEbuf[32] = {0};
char txValue[32] = "dvs";
char test='\0';
// See the following for generating UUIDs: https://www.uuidgenerator.net/
#define SERVICE_UUID "f30fc7e2-ce12-11ed-afa1-0242ac120002"
#define CHARACTERISTIC_UUID_RX "f30fce2c-ce12-11ed-afa1-0242ac120002"
#define CHARACTERISTIC_UUID_TX "f30fcf9e-ce12-11ed-afa1-0242ac120002"
class MyServerCallbacks : public BLEServerCallbacks
{
void onConnect(BLEServer *pServer)
{
Serial.println("COM");
deviceConnected = true;
};
void onDisconnect(BLEServer *pServer)
{
Serial.println("DISCON");
deviceConnected = false;
}
};
class MyCallbacks : public BLECharacteristicCallbacks
{
void onWrite(BLECharacteristic *pCharacteristic)
{
std::string rxValue = pCharacteristic->getValue(); //接收信息
if (rxValue.length() > 0)
{ //向串口输出收到的值
//Serial.print("RX: ");
for (int i = 0; i < rxValue.length(); i++)
{
//Serial.print(rxValue[i]);
Serial.write(rxValue[i]);
}
Serial.println();
}
}
};
void setup()
{
Serial.begin(115200);
// 创建一个 BLE 设备
BLEDevice::init("ZZX");
// 创建一个 BLE 服务
pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks()); //设置回调
BLEService *pService = pServer->createService(SERVICE_UUID);
// 创建一个 BLE 特征
pTxCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_TX, BLECharacteristic::PROPERTY_NOTIFY);
pTxCharacteristic->addDescriptor(new BLE2902());
BLECharacteristic *pRxCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_RX, BLECharacteristic::PROPERTY_WRITE);
pRxCharacteristic->setCallbacks(new MyCallbacks()); //设置回调
pService->start(); // 开始服务
pServer->getAdvertising()->start(); // 开始广播
Serial.println("cting");
}
void loop()
{
// deviceConnected 已连接
if (deviceConnected)
{
if(Serial.available())
{
String message = Serial.readString();
pTxCharacteristic->setValue(message.c_str());
pTxCharacteristic->notify();
}
}
if (!deviceConnected && oldDeviceConnected)// disconnecting 断开连接
{
delay(200); // 留时间给蓝牙缓冲
pServer->startAdvertising(); // 重新广播
Serial.println("start");
oldDeviceConnected = deviceConnected;
}
if (deviceConnected && !oldDeviceConnected)// connecting 正在连接
{
oldDeviceConnected = deviceConnected;// do stuff here on connecting
}
}