serial mystery to me

here is the code: void setup() { Serial.begin(9600); // opens serial port, sets data rate to 9600 bps }

void loop() {

// send data only when you receive data: if (Serial.available() > 0) { // read the incoming byte: incomingByte =; // say what you got: Serial.print("I received: "); Serial.println(incomingByte, DEC); while(Serial.available() > 0){ //flush buffer; } } }

i type one character say 1 hit return and I get the terminal two ?? I received: 49 I received: 10 why am i getting the second char?

I type two char say 22 hit return and get I received: 50 I received: 50 I received: 10

i try to flush all but the first char but to no avail, i also tried using Serial.flush() what's going on? thanks in advance

You are seeing the linefeed character (10) being sent from the Serial monitor. Look bottom/right of the monitor for the line ending options.

BTW, Serial.flush() flushes the send buffer, not the receive buffer

ok - got the newline issue.
if I only want one char how do I flush the rest?

Serial.print() does not add a linefeed.


if I only want one char how do I flush the rest?

Read until nothing is available, but be aware that you can read the serial port much faster than bytes can arrive so although nothing may be available when you check it may become available soon after. It is much netter to have a more robust system, perhaps by reading until a termination byte, such as a newline, is received, then you can do what you like with the bytes received up to that point safe in the knowledge that there is no more data to come.

Even better is to wrap the serial message in both start and end markers such as < and > and read the bytes between them. That way you know that you started reading the message at the start and not part way through.

checking for a newline did it. cheers

The loop() will be executed many times, and the characters arrive slowly into the serial buffer.

Your code checks if there is at least one character in the serial buffer, if yes, read it, and discards the others.. but there is 99.9% chances that those others characters didn't arrive yet in the serial buffer.

A solution is to use a delay(), but I don't like this. A better solution is something lie this:


bool shouldRead = true;

void loop()
  currentTime = millis();
  if ( shouldRead )
    if ( Serial.available() > 0 )
      char c =;
      Serial.println( c );
      shouldRead = false;
      lastReadTime = currentTime;
    while ( Serial.available() > 0 );
    if ( currentTime - lastReadTime >= 1000 )
      shouldRead = true;