This repository has been archived on 2025-11-23. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
RP2040_Resources/1_Basic_GPIO/digitalIn.md

2.5 KiB

Read Button

This example uses gpio_get api call to read and return the logic level of a gpio pin. A button is used to control the logic level of the pin. The connections are made as below. An additional concept called pulling is used to properly switch between high and low.

int buttonPin = 15;
int ledPin = 14;
gpio_init(buttonPin);
gpio_init(ledPin);
gpio_set_dir(buttonPin, GPIO_IN);
gpio_pull_down(buttonPin);
gpio_set_dir(ledPin, GPIO_OUT);

while (true){
gpio_put(ledPin, gpio_get(buttonPin));
sleep_ms(10);
}

The usual gpio_init and gpio_set_dir are used to initialize and set the direction of the pins. Here, the pin which connects to the button gets set as input using GPIO_IN. The button is also configured in pull down configuration. This guide explains the use of pull up and pull down resistors.

  • insert gif of controlling led with button

The same code can be used for controlling the fan from earlier experiment. LED connected to the ledPin is replaced with connection to the gate pin of the mosfet.

  • insert gif of controlling fan with button

ToggleButton

Instead of setting the fan status to be the same as the the button status, this example toggles everytime the button is pressed.

Below code demonstrates using a button to toggle the state of the fan between on and off.

    int buttonStatus = gpio_get(buttonPin);
    bool outputStatus = false;
    int state = buttonStatus * 2 + gpio_get(buttonPin);
    while (true)
    {
        state = buttonStatus * 2 + gpio_get(buttonPin);
        switch (state)
        {
        case 1:
            outputStatus = !outputStatus;
            gpio_put(ledPin, outputStatus);
            buttonStatus = 1;
            sleep_ms(10);
            break;
        case 2:
            buttonStatus = 0;
            sleep_ms(10);
        default:
            break;
        }
    }

To toggle the state on button state changes, change in button press is recorded using buttonStatus variable.

If the button is pressed, buttonState will be 0 and new state will be 1. Hence, the value in the status variable will be 1. When this happens, the fan state is toggled. Output doesn't change when the button is released.

Small delay is added to mitigate switch bouncing, as explained in Circuit Basics blog on switch de-bouncing.

  • insert gif of fan toggling.