Debounce example script (arduino.py) Toggles the on-board LED each time a pushbutton on D2 is pressed, ignoring the contact bounce that makes one press look like several. A new reading only counts once it has stayed the same for DEBOUNCE_MS.
- Wiring
- A pushbutton between D2 and 3.3 V; the pull-down holds D2 at 0 while the button is open.
from arduino import *
BUTTON_PIN = 2
DEBOUNCE_MS = 50
led_state = HIGH
button_state = LOW
last_reading = LOW
last_change_ms = 0
def setup():
pinMode(BUTTON_PIN, INPUT_PULLDOWN)
pinMode(LED_BUILTIN, OUTPUT)
digitalWrite(LED_BUILTIN, led_state)
def loop():
global led_state, button_state, last_reading, last_change_ms
reading = digitalRead(BUTTON_PIN)
if reading != last_reading:
last_change_ms = millis()
if millis() - last_change_ms > DEBOUNCE_MS:
if reading != button_state:
button_state = reading
if button_state == HIGH:
led_state = HIGH if led_state == LOW else LOW
digitalWrite(LED_BUILTIN, led_state)
last_reading = reading
def main():
setup()
while True:
loop()
if __name__ == "__main__":
main()