PAGE 110 OF 150 · MICROCONTROLLERS & LEDS
Reading a Button to Control an LED
Debouncing prevents false multiple presses.
LED SYMBOLTriangle points from anode to cathode; the arrows show light leaving the part.
Reading a button
Connect a button between an input pin and ground, and enable the internal pull-up. The pin reads high normally and low when pressed.
Toggling an LED
- Remember the previous button state.
- When the state changes from high to low, flip the LED state once.
- Ignore changes for 20 to 50 milliseconds to filter bounce.
Common mistakes
- Leaving the input floating, so it reads randomly.
- Toggling every loop while the button is held down.
Detecting the press edge, not the level, fixes the second problem.
REMEMBER
Detect the press edge, not just whether the button is down.Try it yourself
Sketch the circuit on paper first, calculate the values, then build it on a solderless breadboard using a low-voltage supply. Measure with a multimeter before you make anything permanent.
Explore LED clocks, stopwatches and electronics at cosycom.com.