我有一个非常简单的应用程序,我需要通过蓝牙从我的Arduino发送测量数据到我的Ionic应用程序(Android)。
但我对在离子上做正确的方法有疑问。
Arduino代码
char BTString;
/* serial1 is a BluetoothSerial instance */
if (serial1.available()) {
BTString = serial1.read();
/* S is the command that my Ionic application sends to start the measurement */
if (BTString == 'S') {
BTString = "";
/* Here is where I will do the calculations of the measurements and send the results via Bluetooth, but in this example I will only send hypothetical results */
serial1.write("D"); // This indicates Start
serial1.write("45.55"); // measurement 1
serial1.write("79.80"); // measurement 2
serial1.write("67.20"); // measurement 3
serial1.write("F"); // This indicates the end
}
}
离子代码
this._bluetoothSerial.write('S') // Start the measurement
.then((data: any) => {
this.measuring(); // Wait for results
})
.catch((e) => {
this.errorCommBluetooth(); // Error alert
});
private measuring(): void {
this.readOk = false;
do {
this._bluetoothSerial.available()
.then((data: any) => {
this._bluetoothSerial.readUntil('F')
.then((data: any) => {
if (data[0] == 'D') {
this.measurement1 = data[1] + data[2] + data[3] + data[4] + data[5];
this.measurement2 = data[6] + data[7] + data[8] + data[9] + data[10];
this.measurement3 = data[11] + data[12] + data[13] + data[14] + data[15];
this.readOk = true;
}
});
});
}while (this.readOk == false);
}
此代码不起作用。
请问,最好的方法是使用readUntil函数将测量结果存储在3个变量中。
答案 0 :(得分:1)
解决!这段代码对我有用:
this._bluetoothSerial.available()
.then((number: any) => {
this._bluetoothSerial.read()
.then((data: any) => {
if (data[0] == "D" && data[16] == "F") {
this.measure1 = parseFloat(data[1]+data[2]+data[3]+data[4]+data[5]);
this.measure2 = parseFloat(data[6]+data[7]+data[8]+data[9]+data[10]);
this.measure3 = parseFloat(data[11]+data[12]+data[13]+data[14]+data[15]);
this._bluetoothSerial.clear();
}
});
});