#include <CurieBLE.h>
#include <LM35.h>
LM35 temp(A4);
BLEPeripheral blePeripheral; // BLE Peripheral Device (the board you're programming)
BLEService RelayService("19B10010-E8F2-537E-4F6C-D104768A1214"); // BLE LED Service
// BLE LED Switch Characteristic - custom 128-bit UUID, read and writable by central
BLEUnsignedCharCharacteristic switchCharacteristic("19B10011-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
BLEUnsignedIntCharacteristic LM35Data( "19B10012-E8F2-537E-4F6C-D104768A1214", BLERead | BLENotify);
const int RelayPin = 13; // pin to use for the Relay
char control = '0';
int old_data ;
void setup() {
Serial.begin(9600);
// set Light pin to output mode
pinMode( RelayPin, OUTPUT);
// set advertised local name and service UUID:
blePeripheral.setLocalName("LM35");
blePeripheral.setAdvertisedServiceUuid( RelayService.uuid());
// add service and characteristic:
blePeripheral.addAttribute(RelayService);
blePeripheral.addAttribute(switchCharacteristic);
blePeripheral.addAttribute(LM35Data);
// set the initial value for the characeristic:
switchCharacteristic.setValue(0);
// begin advertising BLE Relay service:
blePeripheral.begin();
Serial.println("BLE Relay service.");
}
void loop() {
// listen for BLE peripherals to connect:
BLECentral central = blePeripheral.central();
// if a central is connected to peripheral:
if (central) {
Serial.print("Connected to central: ");
// print the central's MAC address:
Serial.println(central.address());
// while the central is still connected to peripheral:
while (central.connected()) {
// if the remote device wrote to the characteristic,
// use the value to control the Light:
if (switchCharacteristic.written()) {
control = switchCharacteristic.value();
Serial.print("value : ");
Serial.println(control);
if (control == 'O') {
Serial.println("Relay on");
Serial.println(switchCharacteristic.value());
digitalWrite(13, HIGH); // Open relay
} else if(control == 'C'){
Serial.println(F("Relay off"));
Serial.println(switchCharacteristic.value());
digitalWrite(13, LOW); // Close Relay
}
}
int new_data = temp.cel();
if(old_data != new_data)
{
LM35Data.setValue(new_data);
Serial.println(new_data);
old_data = new_data;
delay(1000);
}
}
// when the central disconnects, print it out:
Serial.print(F("Disconnected from central: "));
Serial.println(central.address());
}
}
接下來是Appinventor2程式說明:
Arduino 101 BLE藍牙連線需要MAC序號才可連線成功,每片MAC都不相同,在Arduino101背後QR code下方即可找到,我使用Arduino101的 BLE 藍牙MAC為98:4F:EE:0F:42,每個Arduino101的藍牙MAC都不同。當程式執行時螢幕便會初始化,手機藍牙開始等待連線,當連上Arduino101時,螢幕標題會寫已連線,開始顯示室內溫度。