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

297 Views Asked by At

I'm sending via Bluetooth with an Android App two bytes like this:

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

        }
    }
}

And this is the code I'm using to receive them with 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) 
  {

     ...

  }
}

I don't have any problems sending just one byte (modifying the code to receive just one), but I can't do the same with two bytes. It's always stuck in the while. Any idea of what I'm doing wrong?

Thanks,

1

There are 1 best solutions below

0
On BEST ANSWER

I finally found the problem with help of ST2000. There was a problem of syncronization between sender and receiver. This is the code working properly:

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