2.5 Reading Button Value¶
These pins have both input and output functions, as indicated by their name GPIO (General-purpose input/output). Previously, we used the output function; in this chapter, we will use the input function to input the button value.
As long as one side of the button pin is connected to 3.3v, and the other side pin is connected to GP14, then 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.
A four-pin button is shaped like an H. Its left two pins or right two pins are connected, which means that when it crosses the central gap, it connects two half rows with the same row number. (For example, in my circuit, E23 and F23 are already connected, as are E25 and F25).
Until the button is pressed, the left and right pins are independent of each other and current cannot flow from one side to the other.
2.5_read_button_value.pyfile under the path of
euler-kit/micropythonor copy this code into Thonny, then click “Run Current Script” or simply press F5 to run it.
Don’t forget to click on the “MicroPython (Raspberry Pi Pico)” interpreter in the bottom right corner.
For detailed tutorials, please refer to Open and Run Code Directly.
import machine import utime button = machine.Pin(14, machine.Pin.IN) while True: if button.value() == 1: print("You pressed the button!") utime.sleep(1)
As soon as the code runs, the shell prints “You pressed the button!”
Pull-up Working Mode
The next part is the wiring and code when you use the button in the pull-up mode.
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 button.value() == 0:.
Also see the reference here: