2017-04-23 16 views
0

我正在使用JavaScript應用程序通過藍牙將數字發送到Flora板,具體取決於數字的範圍,LED顯示一定的顏色。該應用程序能夠連接到電路板,但無法點亮LED。該號碼保存在前一頁的會話存儲中。我想將數據從JavaScript應用程序發送到Flora板以通過藍牙在LED上顯示顏色

初始變量是:

var app = {}; // Object holding the functions and variables 
var BluefruitUART = null; // Object holding the BLE device 
var BLEDevice = {}; // Object holding Bluefruit BLE device information 
BLEDevice.name = 'Adafruit Bluefruit LE'; // Bluefruit name 
BLEDevice.services = ['6e400001-b5a3-f393-e0a9-e50e24dcca9e']; // Bluefruit services UUID 
BLEDevice.writeCharacteristicUUID = '6e400002-b5a3-f393-e0a9-e50e24dcca9e'; // Bluefruit writeCharacteristic UUID 

然後發送該消息到Arduino的功能是:

app.sendMessage = function(message, int index) // Send a message to Bluefruit device 
{ 
    var data = evothings.ble.toUtf8(message); 
    BluefruitUART.writeCharacteristic(
     BLEDevice.writeCharacteristicUUID, 
     data, 
     function() { 
      console.log('Sent: ' + message); 
     }, 
     function(errorString) { 
      console.log('BLE writeCharacteristic error: ' + errorString); 
     } 
    ) 
}; 

發送該消息到Arduino的按鈕:

<button class="green wide big" onclick="app.sendMessage('on', sessionStorage.AQI)">ON</button> 

Arduino IDE上的代碼是:

void setup() { 
    pinMode(LEDpin, OUTPUT); 
    Serial.begin(9600); 
    setupBluefruit(); 
} 

void loop() { 
    String message = ""; 
    while (ble.available()) { 
    int c = ble.read(); 
    Serial.print((char)c); 
    message.concat((char)c); 
    if (message == "on, int") { 
     message = ""; 
     Serial.println("\nTurning LED ON"); 
     digitalWrite(LEDpin, HIGH); 
    } 
    else if (message == "off") { 
     message = ""; 
     Serial.println("\nTurning LED OFF"); 
    digitalWrite(LEDpin, LOW); 
    } 
    else if (message.length() > 3) { 
     message = ""; 
    } 
    } 
} 

回答

0

此行這裏:

if (message == "on, int") { 

是消息字符串字面"on, int"比較。然而,在你的實際消息中,你會發送一些實際的數字,而不是字符串"int"。要檢查是否message開始"on",您可以使用startsWith功能,像這樣:

if (message.startsWith("on")) { 

隨着一點點運氣,這將讓LED開啓。

接下來就是實際傳遞一些數字。在你的sendMessage函數中你永遠不會使用index參數,所以你需要改變它來這樣做。然後Arduino的代碼中,你可以解析從字符串這樣的數字,一句:這將砍掉字符串("on ")的前3個字符,其餘轉換爲int

if (message.startsWith("on")) { 
    int index = message.substring(3).toInt(); 

。然後你可以用它來設置LED的顏色。有關Arduino字符串處理功能的更多信息,請參閱here

相關問題