How to use button with Raspberry Pi Pico using micropython

Posted

in

by

The Pico has internal pull up /down circuits inside it.

I have made this simple circuit for demonstration.

Schematic showing LED connected to GP4 and a Button connected to GP22

Button could be connected in two ways.

  1. Internal Pull Up/Down
  2. External Pull UP/Down

In the schematic i connected a button to GP22 using a external pull up of resistor 10k. I also used a capacitor in parallel with the button to debounce the button externally.

Using a external pull-up resistor can also help to protect the GPIO pin from damage due to excessive current flow. Without a pull-up resistor, a short circuit or other electrical fault in the switch or button could potentially allow a large current to flow through the GPIO pin, damaging it or the microcontroller itself.

Sample Code

import machine

# Set up the button on GPIO22 with external pull-up resistor
button = machine.Pin(22, machine.Pin.IN, machine.Pin.PULL_UP)

# Set up the LED on GPIO4
led = machine.Pin(4, machine.Pin.OUT)

# Loop forever
while True:
    # Read the current button value
    curr_button = button.value()

    # If the button is pressed, turn on the LED
    if curr_button == 0:
        led.value(1)
    # Otherwise, turn off the LED
    else:
        led.value(0)

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *