Serial.parseInt() vs Serial.read()?

My code on tinkercad is given below:

int count;//number of led blinks

void setup()
{
  pinMode(13,OUTPUT);
  Serial.begin(9600);
  Serial.println("How many times do you want red led to blink?");
  while (Serial.available() ==0) {}
  count = Serial.parseInt();
}

void loop()
{
  for (int i=0; i<count; i++)
  {
    digitalWrite(13,HIGH);
    delay(500);
    digitalWrite(13, LOW);
    delay(500);
  }
  delay(5000);
}

If i replace Serial.parseInt(); with Serial.read(); it does not work properly . why?
Forexample if i want to blink led two times and i use Serial.parseInt();it works properly but if i use Serial.read(); led keeps on blinking,it does not stop?why?

According to my understanding of below given answers and my latest today experiences, Serial.read();converts the first character of given argument to ASCII while Serial.parseInt();considers the original argument in original form as such without any conversion

Read the documentation of both functions and answer your question yourself.

1 Like

Assume that your sketch contains Serial.read() instead of Serial.parseInt().

You enter 1 from the InputBox of the Serial Monitor, click on the Send Button and then check that the L (LED) blinks for 49 ('1' = 0x31 = 3x16 + 1 = 49) times, which is correct. This observation might help you to understand the difference between Serial.read()/parseInt() commands.

if you typed 2 then it probably blinked 50 times. just be patient

and if you read the docs you'll see why 2 converts into 50

Because Serial.read() and Serial.parseInt() perform COMPLETELY different functions? They are in no way directly interchangeable.

There is one common behavior -- both read the serial buffer.

Serial.parseInt() is specifically designed to return an integer. It will convert the characters it receives into an integer value. For example if you type '1', '3', [Send]... it will return the integer 13.

Serial.read simply returns a single byte... so as above it would return '1'. The character '1' in ASCII is 49 decimal... so it will return 49.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.