SOLVED: Having trouble with serial communication

The following code is supposed to turn on a pin when “C1” is sent and turn off the pin when “C0” is sent. But it only works if I include the “Serial.println(“Hello”);” statement indicated in the comment.

What do I need to do to get the code to see that serial data is available without using that Serial.println statement?

int washerPin = 11;



void setup() {

  // set the slaveSelectPins as outputs and turn to deselect (by setting HIGH):

  pinMode (washerPin, OUTPUT);
  
  // start serial port at 115,200 bits per second
  Serial.begin(115200);
}

void loop(void)
{
      unsigned char cmd, value;
      
      Serial.println("Hello");  // If I take this command out, it does not work
 
      if(Serial.available()) {

        cmd = Serial.read();

 // If it's not a proper command, ignore it and wait for the next command
 if(cmd != 'C') return;

        value = Serial.read();
        
        value = value - '0';

       if (cmd == 'C') {
  
           // If it's not a proper value (between 0 and 1), ignore it and wait for the next command
           if(value < 0 || value > 1) return;
           
           // got the command and value, now do the command
           switch(value) {
             
            case 0:
               digitalWrite(washerPin, LOW);
               break;
  
            case 1:
               digitalWrite(washerPin, HIGH);
               break;
            }
        }  
      }
 }

PS: I should note that I am running this on the Serial Monitor.

Check for one byte...

      if(Serial.available()) {

But read two bytes...

        cmd = Serial.read();
        value = Serial.read();

Oops.

Thank you very much, I changed "if (Serial.available())" to "if (Serial.available() >= 2)" and the code did work in the Serial Monitor.

But that was just a code snippet to test, and when I use my larger piece of code with that change made, it still does not work. I'll try some more tomorrow and post again if I cannot get that to work.

PS: That fix fixed the problem. It wasn't working in the larger piece of code because of an unrelated typographical error. When I fixed that error, it worked.

Apply the principles shown in Serial Input Basics - updated

Thanks, I had found that helpful thread and thought I had everything covered.

The code I have worked when I wrote it 3 or 4 years ago even with the sloppy coding. I am not sure why it suddenly did not work now. But I am glad to have had help from Coding Badly to fix the sloppiness and get working code again.