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

Can't read two bytes through Serial.read - Arduino

我正在通过蓝牙使用 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 中。知道我做错了什么吗?

谢谢,

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