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.
| pressed | lastPressed | What it means |
|---|---|---|
| no | no | nothing happening |
| yes | no | the transition, fires once |
| yes | yes | still held, nothing new |
| no | yes | the 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
loop()gets a new stack every call. Locals are built and destroyed each pass so they cannot remember anything. Globals live in static storage, which is the only place history can goloop()is a function called repeatedly, not a loop- The output state lives in a variable. The pin is just a copy of it
lastPressed = pressedmust sit outside theif. Inside it latches and the button works exactly once. First thing to check when a toggle misbehaves- Contacts bounce 1 to 5ms so one press can look like several. Symptom is the toggle landing on the wrong state, or a button that works half the time
delay(20)dodges bounce by sampling slowly, and it is stilldelay(). 20ms where the board can do nothing else. Themillis()version records when the last edge happened and ignores anything closer than ~20ms, no blocking- Print only inside the
ifand Serial becomes readable. One line per press instead of a wall of text - Compare now against last time keeps coming back. Debouncing, rotary encoders, pulse counting, and the pedestrian button in Traffic Light are all this same four-line shape. Worth getting here while it is small