Serial.read() question

Hello,

I cant figure out what is the problem with this code. For now Serial.read() is a bit tricky to me.

void setup() {                
   Serial.begin(9600); 
   digitalWrite(5,LOW);
 
  }

 void loop() {
       
      if (Serial.available() > 0)
       {
       delay(20);
       int number= Serial.parseInt();
         
       if (number < 3){
          digitalWrite(5,HIGH);
          Serial.println(number);
          Serial.println("Less then 3");
         }


       else if (number > 3){
         
            digitalWrite(5,LOW);
            Serial.println(number);
            Serial.println("More then 3");          
         }
       }
   
}

When i type a number, everything is ok, but after a second, the var "number" is ZERO :open_mouth: I have no idea why.

If i type in the Serial monitor 5 i get this

5
More then 3
0 ????? :cry:
Less then 3 ??????

First, please edit your post to include code tags. See How to use the forum please :slight_smile:

Next, I think I know why you find Serial.read() tricky. That's because you NEVER use it :wink: You use the (stupid) .parseInt() method. Do know this function is a blocking function aka will cause your code to pause.

And now the bonus question, to what is the line ending set in Serial Monitor?

Thanks Septilion for the fast replay.
I have edited the text ,I have code tags now :slight_smile:

"Next, I think I know why you find Serial.read() tricky. That's because you NEVER use it :wink: " - exactly, I'm learning how to use it :slight_smile:

Newline - if that was the question :slight_smile:

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data. There is also a parse example to illustrate how to extract numbers from the received text.

...R

after the number some control characters are send (line end characters \r and/or 'n). parseInt() waits for characters a second (so delay(20) is for nothing). if it can't read a number, it returns 0.

quote author=Dacha011 link=msg=4010964 date=1547031898]
I have edited the text ,I have code tags now :slight_smile:
[/quote]
Thanks!

Dacha011:
exactly, I'm learning how to use it :slight_smile:

For that, indeed have a look at Robin2's fine explanation :slight_smile: Which is indeed a wayyyyy better way to do it.

Dacha011:
Newline - if that was the question :slight_smile:

I Thought that would be the case :wink: So after everything you enter a newline is send. .parseInt() read up to (not inclusive) that newline. So after .parseInt() returns the Serial buffer is still filled with a newline (aka Serial.available() still return >0). So a new .parseInt() is started, ignores every non-digit and times out because there is no digit which returns 0 :slight_smile:

PS "greater than" :wink: Yes, I make the same mistake quite often as well ::slight_smile:

Thanks for the advice, especially about the newline.
The Serial Input Basic tutorial Robin2 posted is quite good :slight_smile: