serial.available() responds to no input

edited December 2017 in Arduino

I've got my laptop connected via Com5 to an Arduino Mega. When strings are sent from the Mega, Processing is responding correctly. However, Processing is also reading "nulls" when it shouldn't. The following code is filling the string with nulls--it seems to me that if (serial.available>0), then the string should have something other than null in it.

if(myPort.available() > 0) {               // If data is available,
  val = myPort.readStringUntil('\n');   }  // read it and store it in val
if(val != null) {
  print(val);                            //print it out in the console
  val = null ; }

Two questions: First, I'm wondering why the first if statement is being entered and second, am I using "null" correctly or do I need single or double quotes around it? Thanks

Answers

  • Answer ✓

    I'm a little confused. In your explanation you talk about Processing reading "nulls", but the code snippet is Arduino source code, but I will try and offer an answer.

    The first if statement is being entered because there are characters in the serial buffer waiting to be read.

    Line 2 reads the characters until the terminating character ('\n' = linefeed) is found in the serial buffer. "val" is assigned a pointer to the null-terminated string. If it is an empty string then val[0] == '\0'.

    As for why would you be getting empty strings, are you using a println("") statement in Processing, or whatever device that is talking to the Arduino?

    Yes, you are using "null" correctly in lines 3 and 5.

  • Thanks for the note regarding the way Processing terminates a serial read, eg, when it sees a linefeed character.

    But I'm still convinced that serial.available() should have been zero, since there was no serial transmission going on unless I manually initiated it. So I'm still looking for that evil start bit.

  • If you are seeing stray characters I suggest you check for interference, or even try a different USB cable -- I'm making broad assumptions here. ;)

Sign In or Register to comment.