我通过蓝牙与Android应用程序发送两个字节,如下所示:
private void _sendCommand(byte command, byte arg)
{
if (CONNECTED)
{
try
{
os.write(new byte[]{command, arg});
os.flush();
} catch (IOException e) {
Log.e(TAG, "Error sending command: " + e.getMessage());
}
}
}
这是我用Arduino接收它们的代码:
byte _instruction;
byte _arg;
void loop()
{
while(Serial.available() < 2)
{
digitalWrite(LED_BUILTIN, HIGH);
}
digitalWrite(LED_BUILTIN, LOW);
_instruction = Serial.read();
_arg = Serial.read();
Serial.flush();
switch (_instruction)
{
...
}
}
我没有任何问题只发送一个字节(修改代码只接收一个字节),但我不能用两个字节做同样的事情。它总是卡在while
中。我知道我做错了什么?
谢谢,
答案 0 :(得分:0)
我终于在ST2000的帮助下找到了问题。发送方和接收方之间存在同步问题。这是代码正常工作:
void loop()
{
// Wait until instruction byte has been received.
while (!Serial.available());
// Instruction should be read. MSB is set to 1
_instruction = (short) Serial.read();
if (_instruction & 0x80)
{
// Wait until arg byte has been received.
while (!Serial.available());
// Read the argument.
_arg = (short) Serial.read();
switch (_instruction)
{
...
}
}
Serial.flush();
}