Raspberry Pi Pico
Buttons & LEDs
This project puts together some pushbuttons and some LEDs. The idea is to have an LED light up when its corresponding button is pressed. I am using these nice LED buttons but you can achieve a similar effect by using separate LEDs and pushbuttons.

This Fritzing shows how you might set this up with the separate components.

When programming the solution, I used binary values for storing the states of the buttons and wrote a procedure to set the LEDs using the same binary value. This makes the LEDs light up when the button is pressed.
import board
from time import sleep
from digitalio import DigitalInOut, Pull, Direction
# function to read buttons into a binary pattern, 1 for pressed
def read_btns(btn_list):
result = 0
for i, b in enumerate(btn_list):
result += (b.value^1)<<i
return result
# tells if a button is pressed
def pressed(pattern, b):
return pattern>>b & 1
# sets leds based on a binary value
def set_leds(led_list, pattern):
for i, l in enumerate(led_list):
l.value = pattern >> i & 1
# set up button pins
btn_pins = [board.GP2, board.GP3, board.GP4, board.GP5]
btns = [DigitalInOut(p) for p in btn_pins]
# set up as buttons
for b in btns:
b.switch_to_input(pull = Pull.UP)
# set up LED pins
led_pins = [board.GP6, board.GP7, board.GP8, board.GP9]
leds = [DigitalInOut(p) for p in led_pins]
# set direction
for l in leds:
l.direction = Direction.OUTPUT
previous = 0
while True:
reading = read_btns(btns)
set_leds(leds, reading)
if reading!=previous:
if pressed(reading, 0):
print("Button 0 was pressed.")
elif pressed(reading,1):
print("Button 1 was pressed.")
elif pressed(reading,2):
print("Button 2 was pressed.")
elif pressed(reading,3):
print("Button 3 was pressed.")
else:
sleep(0.1)
previous = reading
sleep(0.01)

