Blink While a Button Toggles
Part of the Timing Without Delay section of Coddy's Arduino journey. Lesson 5 of 18.
A sketch that never waits can watch a button and run a blink at the same time. Each loop takes a few microseconds, so the board looks at the button thousands of times a second and sees even a very short tap.
The blink is the millis() pattern. The button is the edge check from the Inputs section: act when the button is pressed now and was not pressed on the loop before. ! means "not", so !wasPressed reads "was not pressed".
bool wasPressed = false;
void loop() {
// the blink: if (now - previous >= 500) { ... }
bool pressed = digitalRead(buttonPin) == LOW;
if (pressed && !wasPressed) {
// the button just went down
}
wasPressed = pressed;
}Put both parts in loop(), one after the other, and keep delay() out of both. If the blink waited 500 ms, a tap that starts and ends inside the wait would never be seen.
Challenge
MediumMake the board do two things at once:
- the red LED on pin 13 switches every 500 ms, timed with
millis() - each press of the button switches the yellow LED on pin 12: on, then off, then on
A quick tap must work at any moment, and holding the button switches the yellow LED only once. Press Run, tap the button, then Check.
Try it yourself
const int redLed = 13;
const int yellowLed = 12;
const int buttonPin = 2;
void setup() {
pinMode(redLed, OUTPUT);
pinMode(yellowLed, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
// 1. switch the red LED every 500 ms, with millis()
// 2. each press of the button switches the yellow LED on or off
}
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