A Light on a Timer
Part of the Timing Without Delay section of Coddy's Arduino journey. Lesson 6 of 18.
A stairway light comes on when you press its button and goes off by itself a little later. Press again while it is on, and the time starts over.
That needs two things: the moment of the last press, and whether the light is on. Store the moment in an unsigned long when the button is down:
if (digitalRead(buttonPin) == LOW) {
pressedAt = millis(); // start (or start again) the time
lightOn = true;
digitalWrite(ledPin, HIGH);
}Then, on every loop, check how long it has been:
if (lightOn && millis() - pressedAt >= onTime) {
lightOn = false;
digitalWrite(ledPin, LOW);
}The two parts never wait, so a press is seen at any moment, even while the light is already on. With delay(2000) after the press, a second press during the wait would be lost.
Challenge
EasyBuild a stairway light:
- a press lights the LED on pin 13 at once
- 2 seconds after the press, it goes off by itself
- a press while it is on starts the 2 seconds again
Press Run, press the button a few times, then Check.
Try it yourself
const int ledPin = 13;
const int buttonPin = 2;
const unsigned long onTime = 2000; // how long the light stays on
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
// when the button is down: light the LED and remember the time
// when onTime has passed since then: turn the LED 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