Skip to main content
2 of 2
added 52 characters in body
Nick Gammon
  • 38.9k
  • 13
  • 70
  • 126
Serial.println(Serial.read());
if (Serial.read() == 49) {

You are doing two reads here, not one. So you are reading and displaying, and then reading a second byte (not the one you displayed).

Much better would be:

int cmd = Serial.read();
Serial.println(cmd);
if (cmd == 49)  {
  ... do something ...
} else if (cmd == 50)  {
  .. do something else ...
}

And so on.

Also, why use numbers when you can show the ASCII characters? eg.

int cmd = Serial.read();
Serial.println(cmd);
if (cmd == '1')  {
  ... do something ...
} else if (cmd == '2')  {
  .. do something else ...
}

You may also want to consider using:

if (!Serial.available())
    return;

That way you don't test for serial data that does not exist.

Why the delay?

Nick Gammon
  • 38.9k
  • 13
  • 70
  • 126