我想将数据从JavaScript应用程序发送到植物板,以通过蓝牙在LED上显示颜色



我正在使用JavaScript应用程序通过蓝牙将数字发送到Flora板,这取决于数字的范围,LED显示了一定的颜色。该应用程序能够连接到板,但无法点亮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 = "";
    }
  }
}

此行:

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

将消息字符串与文字"on, int"进行比较。但是,在您的实际消息中,您将发送一些实际数字,而不是字符串"int"。要检查message是否以"on"开头,您可以使用startswith函数,例如:

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

有一点运气,这将使LED打开。

接下来的事情是实际传递一些数字。在您的sendMessage函数中,您实际上永远不会使用index参数,因此您需要更改它才能这样做。然后在Arduino代码内部您可以从字符串中解析数字,类似的内容:

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

将砍掉字符串("on "(的前3个字符,然后将其余的转换为int。然后,您可以使用它来设置LED颜色。有关Arduino String处理功能的更多信息,请参见此处。

最新更新