Skip to content

Using GPIO

Working with basic GPIO

The pinout for GPIO on the Pico 2W can be found here: https://datasheets.raspberrypi.com/picow/pico-2-w-pinout.pdf

The GPIO pins can be set to different functionalities using the method from gpio.h:

void gpio_set_function(uint gpio, gpio_function_t fn);

An overview of the functionality for each pin is at https://www.raspberrypi.com/documentation/pico-sdk/hardware.html#group_hardware_gpio

Write to a GPIO pin

Configure GPIO pin and set as output. Then toggle the pin from code. Measure the result on an oscilloscope - it should toggle between 0V and 3.3V.

    // This configures GPIO pin 15.
    gpio_init(15);
    gpio_set_dir(15, GPIO_OUT);

    // put the following inside the main loop
    gpio_put(15, true); // on
    sleep_ms(100);
    gpio_put(15, false); // off
    sleep_ms(100);

Read from a GPIO pin

Configure GPIO pin and set as input. Then read the pin from code.
Try putting the read inside the loop where you toggle the output pin and connect the output pin with the input pin (use a wire) and see it change.

    gpio_init(14);
    gpio_set_dir(14, GPIO_IN);

    bool isSet = gpio_get(14);
    printf("gpio_14: %d\r\n", isSet);

Trigger interrupt from GPIO input

All GPIO can create interrupts and the interrupt will invoke a callback function. Interrupts can be configured to be set at levels (high/low) or transitions (low->high or high->low).

enum gpio_irq_level {
    GPIO_IRQ_LEVEL_LOW = 0x1u,  ///< IRQ when the GPIO pin is a logical 0
    GPIO_IRQ_LEVEL_HIGH = 0x2u, ///< IRQ when the GPIO pin is a logical 1
    GPIO_IRQ_EDGE_FALL = 0x4u,  ///< IRQ when the GPIO has transitioned from a logical 1 to a logical 0
    GPIO_IRQ_EDGE_RISE = 0x8u,  ///< IRQ when the GPIO has transitioned from a logical 0 to a logical 1
};

Create a callback function. As specified in gpio.h, it must implement the type:

typedef void (*gpio_irq_callback_t)(uint gpio, uint32_t event_mask);

An example, which just printf's, when an interrupt occurs:

void gpio_irq_handler(uint gpio, uint32_t event_mask)
{
    printf("GPIO %d event mask: %d\n", gpio, event_mask);
}

And configure the interrupt, on gpio pin 10, in the main() method:

    gpio_init(10);
    gpio_set_irq_enabled_with_callback(10, GPIO_IRQ_EDGE_RISE | GPIO_IRQ_EDGE_FALL, true, &gpio_irq_handler);

RPi Pico SDK documentation - interrupt : https://www.raspberrypi.com/documentation/pico-sdk/hardware.html#group_hardware_irq - gpio: https://www.raspberrypi.com/documentation/pico-sdk/hardware.html#group_hardware_gpio