Debounce example script (phyduino.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.
import time
import phyduino as mcu
DEBOUNCE_MS = 50
button = mcu.pin("D2", "in", pull="down")
mcu.led.on()
button_state = 0
last_reading = 0
last_change_ms = time.ticks_ms()
while True:
reading = button.value()
if reading != last_reading:
last_change_ms = time.ticks_ms()
if time.ticks_diff(time.ticks_ms(), last_change_ms) > DEBOUNCE_MS:
if reading != button_state:
button_state = reading
if button_state == 1:
mcu.led.toggle()
last_reading = reading