Menu
CoddyTech

Blink Speed From Serial

Part of the Inputs section of Coddy's Arduino journey. Lesson 17 of 22.

Type 250 and the board receives three characters, '2', '5' and '0', then the newline. Serial.parseInt() reads digits and turns them into the number 250, stopping at the first character that is not a digit.

It has a catch: when no digit arrives, parseInt() waits up to 1 second for one, then returns 0. That happens after every number you type: the newline that ended the number is still waiting, so Serial.available() is above 0 again, and parseInt() finds no digit, waits its second and returns 0.

So treat a 0 as "nothing useful" and keep the old value:

if (Serial.available() > 0) {
  int n = Serial.parseInt();
  if (n > 0) {
    wait = n;
  }
}

You will see the LED pause for a second after each number you type: that is parseInt() waiting.

challenge icon

Challenge

Medium

The LED on pin 13 blinks, on for wait ms and off for wait ms, with wait starting at 500. Let the Serial monitor change the speed:

  • when characters are waiting, read a number with Serial.parseInt()
  • if it is above 0, store it in wait

Press Run, send 100 from the Serial monitor, then Check.

Try it yourself

const int ledPin = 13;

int wait = 500;

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

void loop() {
  // when characters are waiting, read a number into wait (if it is above 0)
  digitalWrite(ledPin, HIGH);
  delay(wait);
  digitalWrite(ledPin, LOW);
  delay(wait);
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Inputs

Practice on your own: Arduino playground