Raspberry Pi Pico
Using Pushbuttons

Pushbuttons and toggle switches are digital inputs. We have the choice to read the state of the button or switch and detect, at any time, whether it is closed or open. We can also capture the moment when it changes from one state to another.

Buttons come with two or four pins. When they have four pins like these ones, the horizontally opposite pins are connected. You connect one of them to the digital pin you want to use to read the button and the other pin goes to GND. Here I have connected two pushbuttons to pins 10 and 18 on the Pico.

Pico Circuit

Here is a Fritzing diagram equivalent to the circuit in the photograph,

Pico Circuit

The basic code you need to interact with a button is,

from machine import Pin
from time import sleep

btn_a = Pin(10,Pin.IN,Pin.PULL_UP)

led = Pin(25,Pin.OUT)

# subroutine to handle button presses
def btn_a_handler(pin):
    led.toggle()
    
# attach IRQ to button pin
btn_a.irq(trigger=Pin.IRQ_RISING, handler=btn_a_handler)

When we define a pin for digital inputs, we get to choose the 'PULL' of the pin. This allows us to activate a resistor in the microcontroller that will pull the pin high or low. When we connect the pushbutton as I have here, we need to activate a pull-up resistor. This means that the button is in a high state until you press it, at which point it goes low.

An alternative way to wire a pushbutton would be to connect one pin to 3V and the other pin to a GPIO pin which is pulled down. That would mean that the button would be in a high state when pressed.

I have defined a subroutine for when the button is pressed. It simply toggles the state of the onboard LED that is connected to GP25. The last line of the program connects the button pressing to our subroutine. It specifies that the trigger is the rising edge of the button state change. This is when we release the button (when it goes from low to high). We could have also chosen IRQ_FALLING to have the subroutine fire as we are pressing the button.

Here is a program working with both buttons,

from machine import Pin
from time import sleep

btn_a = Pin(10,Pin.IN,Pin.PULL_UP)
btn_b = Pin(18,Pin.IN,Pin.PULL_UP)

led = Pin(25,Pin.OUT)

# subroutine to handle button presses
def btn_handler(pin):
    if pin==btn_a:
        led.value(1)
    elif pin==btn_b:
        led.value(0)
    
# attach IRQ to button pin
btn_a.irq(trigger=Pin.IRQ_RISING, handler=btn_handler)
btn_b.irq(trigger=Pin.IRQ_RISING, handler=btn_handler)

Study this program and you can see that we can use the same code to handle button presses. The details of the pin that triggered the event are passed to the event handler and we can see which of the buttons was pressed. I am sure that you could predict the way the buttons are going to behave when running this code.