Two LEDs, Two Speeds
Part of the Timing Without Delay section of Coddy's Arduino journey. Lesson 4 of 18.
With delay(), two LEDs blinking at different speeds is a puzzle: each wait holds up the other LED. With millis() it is easy, because nothing waits.
Give each job its own variables: its own last time and its own state. Then give each job its own if in loop(). Every loop, each job checks its own clock and acts only when its time has come:
unsigned long redPrevious = 0;
unsigned long greenPrevious = 0;
void loop() {
unsigned long now = millis();
if (now - redPrevious >= 500) {
redPrevious = now;
// switch the red LED
}
if (now - greenPrevious >= 200) {
greenPrevious = now;
// switch the green LED
}
}The two jobs never get in each other's way. You can add a third and a fourth the same way: one set of variables and one if each.
Never share one last-time variable between two jobs. The faster job resets it so often that the slower one never reaches its interval.
Challenge
EasyThe red LED on pin 13 already switches every 500 ms. Make the green LED on pin 12 switch every 200 ms at the same time:
- add
greenPreviousandgreenStatevariables - add a second
ifinloop()for the green LED
Press Run and watch both blink, then Check.
Try it yourself
const int redLed = 13;
const int greenLed = 12;
unsigned long redPrevious = 0;
int redState = LOW;
// add the green LED's two variables here
void setup() {
pinMode(redLed, OUTPUT);
pinMode(greenLed, OUTPUT);
}
void loop() {
unsigned long now = millis();
// the red LED switches every 500 ms
if (now - redPrevious >= 500) {
redPrevious = now;
if (redState == LOW) {
redState = HIGH;
} else {
redState = LOW;
}
digitalWrite(redLed, redState);
}
// make the green LED switch every 200 ms here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Timing Without Delay
1millis()
The millis() ClockTimes in unsigned longBlink Without DelayTwo LEDs, Two SpeedsBlink While a Button TogglesA Light on a TimerPractice on your own: Arduino playground