Serial read question (newbie)

Hi,

I'm a complete newbie, and I'm trying some stuff out.

Why doesn't this work as I expect?
What I want to do is use the serial monitor to send a number (as text) and the Arduino should blink the number of times sent. It seems to read only the first byte. If I add a delay of 50, it still does weird things... Am I supposed to read the number of bytes returned by Serial.available() instead of just looping and checking if there's more?

Thanks a million!

int outputPin = 13;
int val;
int counter;
int nrOfTimesToBlink;

void setup()
{
  Serial.begin(9600);
  pinMode(outputPin, OUTPUT);
}

void loop()
{
  counter = 0;
  val = 0;
  nrOfTimesToBlink = 0;
  while (Serial.available() > 0) {
    val = Serial.read() - 48;
    if (val >= 0 && val < 10)
      nrOfTimesToBlink = (nrOfTimesToBlink * 10) + val;
  }
  
  while (counter < nrOfTimesToBlink) {
    digitalWrite(outputPin, HIGH);
    delay(200);
     digitalWrite(outputPin, LOW);
    delay(200);
    counter++;
  }
}

Arduino Diecemilla
Arduino - 0011 Alpha
Ubuntu Linux 8.10

MrWhammy,

The problem is that Serial is slow compared to the Arduino. Let's say you typed "50" in the serial monitor. As soon as that first '5' arrives, Serial.available() returns 1, your top loop goes to work and nrOfTimesToBlink is set to 5. Now Serial.available is called again. The '0' still isn't due to arrive until many, many microseconds later, so the loop terminates and the second loop causes 5 blinks. Now we're back up to the top. The '0' has arrived. This causes nrOftimesToBlink to be set to 0, with obvious results.

Two solutions come to mind: (a) force the count to be exactly 2 characters long and wait in the top loop until Serial.available() == 2, or (b) invent some kind of termination character, like $, that you must type, and break out of the upper loop only when you see it.

Mikal

Great, understood, thanks!!!

It's now blinking 1268 times :slight_smile:

In response, I hope, to a request for 1268 blinks? Excellent! :slight_smile: