2.5 - Reading Button Value

From the name of GPIO (General-purpose input/output), we can see that these pins have both input and output functions. In the previous lessons, we used the output function, in this chapter we will use the input function to input read the button value.

Schematic

sch_button

One side of the button pin is connected to 3.3v, and the other side pin is connected to GP14, so when the button is pressed, GP14 will be high. However, when the button is not pressed, GP14 is in a suspended state and may be high or low. In order to get a stable low level when the button is not pressed, GP14 needs to be reconnected to GND through a 10K pull-down resistor.

Wiring

wiring_button

Note

We can think of the four-legged button as an H-shaped button. Its left (right) two feet are connected, which means that after it straddles the central dividing line, it will connect the two half rows of the same row number together. (For example, in my circuit, E23 and F23 have been connected, as are E25 and F25).

Before the button is pressed, the left and right sides are independent of each other, and current cannot flow from one side to the other.

Code

Note

  • You can open the file 2.5_reading_button_value.ino under the path of kepler-kit-main/arduino/2.5_reading_button_value.

  • Or copy this code into Arduino IDE.

  • For detailed tutorials, please refer to Open & Run Code Directly.

  • Or run this code directly in the Arduino Web Editor.

Don’t forget to select the Raspberry Pi Pico W board and the correct port before clicking the Upload button.

After the code runs, Click the magnifying glass icon in the upper right corner of the Arduino IDE (Serial Monitor).

ars_serial_monitor

Now, when you press the button, the Serial Monitor will print “You pressed the button!”.

ars_baud_rate

How it works?

To enable Serial Monitor, you need to start serial communication in setup() and set the datarate to 9600.

Serial.begin(115200);

For button, we need to set their mode to INPUT in order to be able to get their values.

pinMode(buttonPin, INPUT);

Read the status of the buttonPin in loop() and assign it to the variable buttonState.

buttonState = digitalRead(buttonPin);

If the buttonState is HIGH, the LED will flash. print “You pressed the button!” on the Serial monitor.

if (buttonState == HIGH) {
    Serial.println("You pressed the button!");
}

Pull-up Working Mode

Next is the wiring and code when the button in the pull-up working mode, please try it.

wiring_button_pullup

The only difference you will see with the pull-down mode is that the 10K resistor is connected to 3.3V and the button is connected to GND, so that when the button is pressed, GP14 will get a low level, which is the opposite of the value obtained in pull-down mode. So just change this code to if (buttonState == LOW).