Toggle on Each Press
Part of the Inputs section of Coddy's Arduino journey. Lesson 4 of 22.
So far the LED has copied the button: on while held, off when let go. A lamp switch works differently: press once for on, press again for off. That is a toggle.
To toggle, the sketch must notice the moment the button goes down: pressed now, but not pressed the last time loop() ran. That moment is called an edge. Keep the last reading in a variable above setup(), like a counter:
int lastReading = HIGH;
void loop() {
int reading = digitalRead(2);
if (reading == LOW && lastReading == HIGH) {
// the button has gone down
}
lastReading = reading;
}Holding the button keeps the reading LOW, so the edge happens once per press, however long you hold it.
To flip a bool, use !, which means "not": ledOn = !ledOn; turns true into false and back.
Challenge
MediumThe button is on pin 2 (INPUT_PULLUP) and the LED on pin 13. Make each press toggle the LED:
- when the button goes down (
LOWnow,HIGHlast time), flipledOn - save the reading in
lastReadingat the end ofloop() - turn the LED on or off to match
ledOn
Press Run, press the button a few times, then Check.
Try it yourself
const int buttonPin = 2;
const int ledPin = 13;
bool ledOn = false;
int lastReading = HIGH;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop() {
int reading = digitalRead(buttonPin);
// flip ledOn when the button goes down
// remember this reading for next time
// turn the LED on or off to match ledOn
}
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