typestar

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

  1. fanOn and lastReading persist between iterations.
  2. The edge test — LOW now, HIGH before — fires once per press.
  3. fanOn = !fanOn toggles; the ternary drives the pin.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Digital I/O, step 5 of 27 in Language basics.

← Previous Next →