Arduino Nano 33 BLE batteryLevel判断接触动作
Arduino Nano 33 BLE batteryLevel判断接触动作
Phyphox BLE的扩展主推Ardoino的几款新发布的Nano 33,而ESP32是列在推荐最后的。
但是,目前来看,Phyphox BLE对Arduino Nano 33 BLE系列支持得并不好,烧录之后的板子,在Phyphox里能找到设备但却不能从设备正常加载Phyphox实验。十分显然,挽救Nano 33BLE的一个途径是:直接在Phyphox editor里面创作实验,或者用ESP32创作实验,然后把实验再放到Phyphox editor里面进行二次加工。但不论怎样,企图直接象ESP32那样方便易用的BLE,似乎很难做到。
但Nano 33 BLE有一些低功耗蓝牙独有的功能,自然就可创作一些另类的应用。本例使用batteryLevel来判断A0脚是不是有人用干燥的手接触了?未来可能尝试用作接触开关,而不需要按压等动作,小球走过去就行了。使用nRF Connect调试,可以看到Characteristic UUID为
00002101-0000-1000-8000-00805f9b34fb
读到了A0的模拟电压值,以16进制返回:
烧录场面:
程序代码。代码里指定了Characteristic,未来在Pyphox editor里面可以通过Service调用它返回来的数值:
#include <ArduinoBLE.h>
BLEService batteryService("1101");
BLEUnsignedCharCharacteristic batteryLevelChar("2101", BLERead | BLENotify);
void setup() {
Serial.begin(9600);
//while (!Serial);//注释掉可随时调试,不注释只能在Serial Monitor里
pinMode(LED_BUILTIN, OUTPUT);
if (!BLE.begin())
{
Serial.println("starting BLE failed!");
while (1);
}
BLE.setLocalName("BatteryMonitor");
BLE.setAdvertisedService(batteryService);
batteryService.addCharacteristic(batteryLevelChar);
BLE.addService(batteryService);
BLE.advertise();
Serial.println("Bluetooth device active, waiting for connections...");
}
void loop()
{
BLEDevice central = BLE.central();
if (central)
{
Serial.print("Connected to central: ");
Serial.println(central.address());
digitalWrite(LED_BUILTIN, HIGH);
while (central.connected()) {
int battery = analogRead(A0);
int batteryLevel = map(battery, 0, 1023, 0, 100);
Serial.print("Battery Level % is now: ");
Serial.println(batteryLevel);
batteryLevelChar.writeValue(batteryLevel);
delay(200);
}
}
digitalWrite(LED_BUILTIN, LOW);
Serial.print("Disconnected from central: ");
Serial.println(central.address());
}