Fresh Pair of Eyes Needed

This is going to be embarrassingly obvious, but a lack of sleep and looking too closely has blinded me to the obvious:

void setup() {
  Serial.begin(9600);
  int v=0;                                     // The value being constructed from individual characters
  Serial.println("Input an integer value:");
  while(Serial.available()==0) {}              // Wait for input
  while(Serial.available()>0) {                // While there are characters to process...
    v*=10;                                     // Shift v
    v+=Serial.read()-48;                       // Add next character to v (-48 converts from ASCII to decimal)
    Serial.println(v,DEC);  //COMMENT OUT TO GET THE PROBLEM
  }
  Serial.print("Constructed integer value: ");
  Serial.println(v,DEC);
}

void loop() {
}

If you remove the Serial.println statement as indicated, see what happens to the output. -only the first digit is processed. The question is, why?

The ATmega's processor is orders of magnitude faster than serial I/O. Your code incorrectly assumes that the whole string has been transmitted once the first character shows up.

By sticking the serial.print() in there, you effectively delay the input processing enough to allow all the characters to arrive.

-j

slaps forehead

Of course! It isn't synchronous!

See, I said it would be embarrassingly obvious!

Cheers mate :slight_smile:

Quick update: a 5 millisecond delay between the two while loops is enough to allow a 5-digit number to get itself up to the board at 9600 baud.

Thanks once again.

Receiving a byte at 9600 baud takes just a bit more than 1ms, so a 2ms delay would suffice.

A better (baud rate independent, requiring minimal time) method would be to simply wait until serial.available() returns 5 if you are always expecting exactly 5 digits. Another method is to built up the integer until you read a newline character (or some other terminator).

-j

Thanks for that. What began as a quick and nasty method of dropping into a service mode and changing some tuning variables on the fly looks like becoming a bit of a library!