Serial.available() question

Why does code below, for one keystroke ('T' in this example), generate twice the Serial.print() as shown here:

 print x : T
0
 print x : 

0

int n;

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  n = Serial.available();
  if (Serial.available())
  {
    char x = Serial.read();
    Serial.print(F(" print x : "));
    Serial.println(x);
    n = Serial.available();
    Serial.println(n);
  }
}

If the sender sends a line-ending character there are two characters in the buffer
hence two times printing and the second printing is just the line feed or carriage return which is unvisible

best regards Stefan

1 Like

Why not simply test 'n'?

Right that first line is superfluous.
Doing away with n saves 2 bytes if memory.

How to get rid of the carriage return character in the serial buffer, or at least prevent getting the serial output printed twice?

Test for it.
It has known value.

I can clearly see a 'T' between the first ':' and the '0'
And a NEWLINE between the second ':' and the '0'

I could even explain why the third Serial.available() returns (and prints) 0.
The question is rather, how many loops did run idle, until the NEWLINE arrived and triggered the second output.

1 Like

It didn't need to be global in the first place

But how is the Serial.print() prevented from being written twice when entering a single character?

What do you mean?

Typing for example 'T' in the serial monitor writes twice the text "print..."

Solved. It simply is a setting in the serial monitor window.

So why did you write it was prevented?

If messages/commands consist of more than one character, it's often convenient to separate them by delimiters.
A newline character is quite common for this purpose.

Sometimes you even want to ignore trailing spaces, which are really hard to see.

And you should be aware of different line separator characters, stemming from Stone Age Teletypes
0x0D = carriage return
0x0A = line feed
(See the options in SerialMonitor)

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