Bodgers – Buttons

This week we are looking at using buttons on our Raspberry Pi Picos.

Connect the LEDs and Buttons to the Pico as shown below:

Next use the code below to test the LEDs

from machine import Pin
from time import sleep

red_led = Pin(15, Pin.OUT)
green_led = Pin(14, Pin.OUT)

def blink():
    red_led.value(1)
    sleep(0.5)
    red_led.value(0)
    green_led.value(1)
    sleep(0.5)
    green_led.value(0)

while True:
    blink()

Next we’ll test the buttons using the following code:

from machine import Pin
from time import sleep

button_1 = Pin(18, Pin.IN, Pin.PULL_UP)
button_2 = Pin(19, Pin.IN, Pin.PULL_UP)

while True:
    if button_1.value() == 0:
        print("Button 1 is Pressed")
    if button_2.value() == 0:
        print("Button 2 is Pressed")
    sleep(0.1)

This week’s challenge is create a program called buttons_leds.py that turns on the red LED and turns off the green LED when button 1 is pressed and when button 2 is pressed will turn the green one on and the red one off.

Leave a comment