Serial read


I would be very grateful if somebody could explain the following outcome of the serial communication.

I am using some global variables (datatype char and byte) to make decisions in the "loop" part of the code. The variables get modified over the serial input buffer, where I read 2 bytes and act accordingly (please see the code below)

while(Serial.available() > 1) { // wait for 2 bytes
      // prefix command 
      prefix_command = (char);     

      if(prefix_command == 'r') {
          command_r = (char);          

      else if(prefix_command == 'f') {
          command_f = (char);                 

      else if(prefix_command == 'E') {
          eeprom_data = (byte);

      else Serial.println("ERROR");      

If I open the serial monitor and send two bytes of data (ascii format), for example r0, the first "if" condition is met and the "command_r" is modified to '0'. This works for all modes and I have no problem here.

The question I have follows: If I send two bytes of data, the values get modified, but not before the "ERROR" is printed out. Why is this happening? It may be very obvious, but I really can't tell.

Also I will be trying to implement CRC checking for my data over the serial, sending ~100 bytes (so CRC-16 should be okay right?). Do you have any pointers about calculating the CRC checksum? Are there any tested (optimized) libraries that could be used with arduino (basically I have a custom board with Atmega 328p)?

Thank you very much and best regards, K

What is your line ending set to in the serial monitor? You may be sending a newline and/or a carriage-return as well.

Your method is not what I would recommend. Please read:

Dear Mr. Gammon,

thank you very much for the answer. I will read the link you have provided with great interest.

Best regards, K