Zach Christensen
arduino journey
P03bFirst LightSession 3✓ Working

Button Toggle

Press on, press off. The program has to remember something now.

Carried forward fromP03 Button LED
Running

The sketch

03b_Button_Toggle.inocomments stripped
const uint8_t PIN_LED = 9;const uint8_t PIN_BTN = 2;bool ledOn = false;bool lastPressed = false;void setup() {  pinMode(PIN_BTN, INPUT_PULLUP);  pinMode(PIN_LED, OUTPUT);  Serial.begin(9600);}void loop() {  bool pressed = (digitalRead(PIN_BTN) == LOW);  if (pressed && !lastPressed) {    ledOn = !ledOn;    digitalWrite(PIN_LED, ledOn);    Serial.println(ledOn ? "LED ON" : "LED OFF");  }  lastPressed = pressed;  delay(20);}

Nothing rewired from Button LED. Same LED, same button, same pull-up. Only the code changed, and the behaviour changed completely.

Level and edge

The last sketch asked "is it down right now", which is a level. This one asks "did it just change", which is an edge. An edge does not exist on the pin. A pin only has a voltage. An edge only exists as a comparison between two samples in time, so detecting one requires storing the previous sample. The variable is not a style choice, it falls out of the physics.

pressedlastPressedWhat it means
nononothing happening
yesnothe transition, fires once
yesyesstill held, nothing new
noyesthe release event, usable if I want it

A 100ms human press covers hundreds of loop iterations. Acting on the level would flip the LED hundreds of times per press and land on a coin flip. Acting on the transition fires exactly once.

What I learned