# Reads the onboard user push button with software debounce on Raspberry Pi Pico / YD-RP2040 (GP24).

from machine import Pin
import time

# Button pin configuration (active LOW with internal pull-up resistor on GP24)
BUTTON_PIN = 24

# Contact debounce stabilization time in milliseconds
DEBOUNCE_TIME = 20  # ms

# Initialize GPIO pin as digital input with internal pull-up resistor
button = Pin(BUTTON_PIN, Pin.IN, Pin.PULL_UP)

# Variables for tracking button state and debounce timing
last_steady_state = button.value()      # Confirmed steady button state
last_flickerable_state = button.value() # Instantaneous state from previous iteration
last_debounce_time = time.ticks_ms()    # Timestamp of the last input transition

print("Button monitoring started. Press the USR button on board...")

while True:
    current_state = button.value()
    current_time = time.ticks_ms()

    # Detect any signal transition (potential contact bounce or valid press)
    if current_state != last_flickerable_state:
        last_debounce_time = current_time

    last_flickerable_state = current_state

    # Check if the signal has remained stable longer than DEBOUNCE_TIME
    if time.ticks_diff(current_time, last_debounce_time) > DEBOUNCE_TIME:
        # Detect confirmed edge transition
        if current_state != last_steady_state:
            if last_steady_state == 1 and current_state == 0:
                print("-> Button PRESSED (Falling edge, Active LOW)")
            elif last_steady_state == 0 and current_state == 1:
                print("<- Button RELEASED (Rising edge)")

            last_steady_state = current_state