Blink on Command
Part of the Inputs section of Coddy's Arduino journey. Lesson 18 of 22.
Type 3 and the LED should blink three times, then stop. loop() already repeats, so let it do the counting: keep a variable with the number of blinks still to do. Each time loop() runs, if there are blinks left, blink once and take one away.
int blinksLeft = 0;
void loop() {
// a number from the Serial monitor sets blinksLeft
if (blinksLeft > 0) {
// one blink
blinksLeft = blinksLeft - 1;
}
}When blinksLeft reaches 0, the if is false and the LED stays dark until the next number.
The newline after the number still makes parseInt() return 0 a second later. Ignore the 0 as before, or it would wipe out the blinks still to do.
Challenge
MediumBlink the LED on pin 13 as many times as the number typed into the Serial monitor:
- when characters are waiting, read a number with
parseInt(), and store it inblinksLeftif it is above 0 - if
blinksLeftis above 0, blink once (200 ms on, 200 ms off) and take one away
Press Run, send 3 from the Serial monitor, then Check.
Try it yourself
const int ledPin = 13;
int blinksLeft = 0;
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
// a number from the Serial monitor sets blinksLeft
// while blinksLeft is above 0, blink once and take one away
}
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