【Curie Nano】Curie Nano BLE初学(一)
之前没有自己开发过蓝牙,就用过HC-05串口蓝牙模块,学习蓝牙必须从头开始了,Curie Nano内部集成了低功耗蓝牙,方便实现互连。如果不学习如何使用Curie自带的蓝牙的话,感觉就是一种资源浪费。依葫芦画瓢,现在对于蓝牙的协议不了解,就先看自带的例子去学习。好在例子里有注释,这个例子通过手机蓝牙可以控制Curie Nano上的LED灯的亮灭,同时,也可以通过按钮的电平变化去控制LED。和蓝牙设置有关的部分在setup函数中,自己可以在loop函数中稍微改动一下就可以实现一些其他IO的控制等#include <CurieBLE.h>
const int ledPin = 13; // set ledPin to on-board LED
const int buttonPin = 4; // set buttonPin to digital pin 4
BLEService ledService("19B10010-E8F2-537E-4F6C-D104768A1214"); // create service
// create switch characteristic and allow remote device to read and write
BLECharCharacteristic ledCharacteristic("19B10011-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
// create button characteristic and allow remote device to get notifications
BLECharCharacteristic buttonCharacteristic("19B10012-E8F2-537E-4F6C-D104768A1214", BLERead | BLENotify); // allows remote device to get notifications
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT); // use the LED on pin 13 as an output
pinMode(buttonPin, INPUT); // use button pin 4 as an input
// begin initialization
BLE.begin();
// set the local name peripheral advertises
BLE.setLocalName("BtnLED");
// set the UUID for the service this peripheral advertises:
BLE.setAdvertisedService(ledService);
// add the characteristics to the service
ledService.addCharacteristic(ledCharacteristic);
ledService.addCharacteristic(buttonCharacteristic);
// add the service
BLE.addService(ledService);
ledCharacteristic.setValue(0);
buttonCharacteristic.setValue(0);
// start advertising
BLE.advertise();
Serial.println("Bluetooth device active, waiting for connections...");
}
void loop() {
// poll for BLE events
BLE.poll();
// read the current button pin state
char buttonValue = digitalRead(buttonPin);
// has the value changed since the last read
boolean buttonChanged = (buttonCharacteristic.value() != buttonValue);
if (buttonChanged) {
// button state changed, update characteristics
ledCharacteristic.setValue(buttonValue);
buttonCharacteristic.setValue(buttonValue);
}
if (ledCharacteristic.written() || buttonChanged) {
// update LED, either central has written to characteristic or button state has changed
if (ledCharacteristic.value()) {
Serial.println("LED on");
digitalWrite(ledPin, HIGH);
} else {
Serial.println("LED off");
digitalWrite(ledPin, LOW);
}
}
}将代码编译烧写后,打开手机调试软件,打开蓝牙,连接成功后,通过写入0和非零的数就可以控制LED的亮灭,通过也可以查看按钮对应引脚的高低电平。点击向上的***后弹出发送数值的界面,写入0或1就可以看到LED对应的变化。
上传一下调试软件,方便下载
页:
[1]