Raspberry Pi Pico Button Toggle LED
Button + LED — next level! Unlike the basic button project, there is no need to hold the button. Press and release → LED on. Press and release again → LED off (toggle). Same circuit (LED GP14, Button GP2), but big code difference. Learn edge detection (capturing the 1→0 falling moment), state tracking, debounce (mechanical bounce filter). MicroPython's led.toggle() swaps state in one line. Foundation of all interactive button projects (mode switcher, IRQ, double-click).

Video
Elektr sxemasi

Manba kodi
1# ─────────────────────────────────────────
2# BlueGrays · bluegrays.com
3# Raspberry Pi Pico Button Toggle LED (GP14 + GP2)
4# ─────────────────────────────────────────
5# Each button press toggles the LED (toggle mode): press for on, press
6# again for off. The code waits for the release, and a 50 ms debounce
7# prevents false triggers.
8#
9# Pins:
10# GP14 -> Red LED (with a 220 ohm resistor)
11# GP2 -> Button (other leg to GND)
12
13from machine import Pin
14from time import sleep_ms
15
16led = Pin(14, Pin.OUT)
17button = Pin(2, Pin.IN, Pin.PULL_UP) # PULL_UP: pressed = 0
18
19while True:
20 # Wait for button press
21 while button.value() == 1:
22 sleep_ms(10)
23
24 # Pressed: toggle the LED
25 led.toggle()
26 sleep_ms(50) # Skip the press bounce
27
28 # Wait for button release
29 while button.value() == 0:
30 sleep_ms(10)
31
32 # Wait after bounce (debounce)
33 sleep_ms(50)
34
Ko‘p so‘raladigan savollar
What is edge detection?
Instead of checking whether the button is held down, you look for the moment its state changes. With a pull-up, the instant the pin drops from 1 to 0 counts as one press, so holding the button doesn't toggle again and again.
What should the debounce time be?
The current code waits with sleep_ms(50) after detecting that the button has been released; it does not measure the time since the last valid press. More robust debouncing requires checking that the input remains stable for a set period.
Why doesn't the LED state always change correctly?
Without debounce, one press can be counted several times and the LED flips twice, ending up where it started. Make sure you store the previous state correctly and that the wait time is long enough.
Are led.toggle() and led.value(not led.value()) the same?
Yes, both invert the LED's state. toggle() is just shorter and easier to read.
