无法通过 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();
}

最新更新