Toggle on press in Arduino
A state variable remembers across loop passes; ! flips it.
// A state variable remembers across loop passes; ! flips it.
const int BUTTON_PIN = 2;
const int FAN_PIN = 5;
bool fanOn = false;
int lastReading = HIGH;
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(FAN_PIN, OUTPUT);
}
void loop() {
int reading = digitalRead(BUTTON_PIN);
if (reading == LOW && lastReading == HIGH) {
fanOn = !fanOn;
digitalWrite(FAN_PIN, fanOn ? HIGH : LOW);
}
lastReading = reading;
}
How it works
fanOnandlastReadingpersist between iterations.- The edge test — LOW now, HIGH before — fires once per press.
fanOn = !fanOntoggles; the ternary drives the pin.
Keywords and builtins used here
HIGHINPUT_PULLUPLOWOUTPUTboolconstdigitalReaddigitalWritefalseifintlooppinModesetupvoid
The run, in numbers
- Lines
- 20
- Characters to type
- 419
- Tokens
- 92
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 85 seconds.
Step 2 of 3 in Digital I/O, step 5 of 27 in Language basics.