< All Topics
Print

Interrupts

Button-Controlled LED with Interrupt-Style Debouncing
# Button-controlled LED with interrupt-style approach and debouncing
# For Arduino Nano RP2040 Connect
import board
import time
from digitalio import DigitalInOut, Direction, Pull
import keypad

# Set up the LED
led = DigitalInOut(board.D13)
led.direction = Direction.OUTPUT

# Set up the button with keypad module
# The keypad module provides event-based detection (like interrupts)
# value_when_pressed=False means the pin reads LOW when button is pressed
# pull=True enables the internal pull-up resistor
button = keypad.Keys((board.D2,), value_when_pressed=False, pull=True)

# Variables for state management
led_state = False  # LED starts off
last_press_time = 0
debounce_delay = 0.05  # 50ms debounce time

print("Press the button on D2 to toggle the LED on D13")

while True:
    # Check for button events
    event = button.events.get()
    
    # If there's an event and it's a press
    if event and event.pressed:
        current_time = time.monotonic()
        
        # Check if enough time has passed since the last press (debounce)
        if current_time - last_press_time > debounce_delay:
            # Toggle the LED state
            led_state = not led_state
            led.value = led_state
            
            # Print the new state
            if led_state:
                print("LED ON")
            else:
                print("LED OFF")
                
            # Update the last press time
            last_press_time = current_time
    
    # You can do other tasks here without blocking or missing button presses
    # The keypad module keeps track of events even if we're busy with other code
    
    # Small delay to prevent using 100% CPU
    time.sleep(0.01)
Table of Contents