无法通过Serial.read读取两个字节 - Arduino

时间:2017-01-01 13:07:06

标签: android bluetooth arduino serial-communication

我通过蓝牙与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中。我知道我做错了什么?

谢谢,

1 个答案:

答案 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();
}