-1

I have a piece of code as shown, and I wish to print the value I send using serial monitor along with a message: "Writing data to slave...".

enter image description here

But everytime I enter a character/number in the serial monitor(like 'a' as shown), the loop runs two times instead of just once. It seems like an extra character(somewhat invisible or null) is being sent along with the typed character.

enter image description here

If I use the condition (Serial.available()>1) then the loop runs just once on sending one character.

Why is this so?

1
  • 2
    Please copy the code as text instead of bad screen dumps. Jan 29 '20 at 15:22
0

I suspect an end of line character is send (probably \n or \r, see comment of Edgar Bonet), or an end of string (0 character).

You can easily find it out by printing the integer value of the character:

char c = serial.read();
Serial.print((int) c);
2
  • 2
    Actually '\n' = 10 (a.k.a. LF, line feed, new line), not to be confused with '\r' = 13 (CR, carriage return). And yes, it's a '\n', as attested by the selection “Newline” on the drop-down menu at the bottom. The other options of this menu are “No line ending”, “Carriage return” and “Both NL and CR”. Note that the last options sends CR before LF. Jan 29 '20 at 16:24
  • @EdgarBonet Thanks for your clarification, I put a forward to your comment. It's always better to check the exact character(s) which ends a line. Jan 29 '20 at 16:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.