|
| 1 | +print("button.py running") |
| 2 | + |
| 3 | +from machine import Pin, Timer |
| 4 | +import time |
| 5 | + |
| 6 | +# Configure IO0 as input with pull-up resistor |
| 7 | +button = Pin(0, Pin.IN, Pin.PULL_UP) |
| 8 | + |
| 9 | +# Variables for long press detection |
| 10 | +long_press_duration = 4000 |
| 11 | +press_start_time = 0 |
| 12 | +is_pressed = False |
| 13 | + |
| 14 | +# Timer for checking long press |
| 15 | +timer = Timer(-1) |
| 16 | + |
| 17 | + |
| 18 | +def on_long_press(t): # Callback for when long press duration is reached. |
| 19 | + timer.deinit() # Stop the timer |
| 20 | + global is_pressed |
| 21 | + if is_pressed and button.value() == 0: # Ensure button is still pressed |
| 22 | + print("Button IO0 long pressed, going into bootloader mode...") |
| 23 | + import machine |
| 24 | + machine.bootloader() |
| 25 | + else: |
| 26 | + is_pressed = False |
| 27 | + |
| 28 | + |
| 29 | +def button_handler(pin): |
| 30 | + """Interrupt handler for button press and release.""" |
| 31 | + global press_start_time, is_pressed |
| 32 | + # Debounce: Ignore interrupts within 50ms of the last event |
| 33 | + if time.ticks_diff(time.ticks_ms(), press_start_time) < 50: |
| 34 | + return |
| 35 | + if button.value() == 0: # Button pressed (LOW due to pull-up) |
| 36 | + print("Button IO0 pressed.") |
| 37 | + press_start_time = time.ticks_ms() |
| 38 | + is_pressed = True |
| 39 | + # Start timer to check for long press after long_press_duration |
| 40 | + timer.init(mode=Timer.ONE_SHOT, period=long_press_duration, callback=on_long_press) |
| 41 | + else: # Button released (HIGH) |
| 42 | + print("Button IO0 released.") |
| 43 | + timer.deinit() # Cancel timer if button is released early |
| 44 | + is_pressed = False |
| 45 | + |
| 46 | + |
| 47 | +# Set up interrupt for both falling (press) and rising (release) edges |
| 48 | +button.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=button_handler) |
| 49 | + |
| 50 | +print("button.py finished") |
0 commit comments