User Guide
Table Of Contents
168
2. At the top of the script, type the following
statements:
import RPi.GPIO
RPi.GPIO.setmode(RPi.GPIO.BCM)
Now you need to configure GPIO2 as an input and enable the
internal pull-up resistors:
• Add the following statement on one line:
RPi.GPIO.setup(2, RPi.GPIO.IN,
pull_up_down=RPi.GPIO.PUD_UP)
The pull_up_down parameter can be one of three values:
Add the remainder of the code to the script:
while True:
if RPi.GPIO.input(2) == RPi.GPIO.LOW:
print("Switch pressed.")
break
RPi.GPIO.cleanup()
This script loops until the switch is pressed and GPIO2 goes low.
At that point, it prints a message to the user, breaks from the
while loop and then releases its control over the GPIO pin.
7.6 Communication between 3.3 V and 5 V Devices
Even though the Pi has a 5 V power supply, it is a 3.3 V device
and 3.3 V is the maximum voltage that you can safely connect to
its input pins. However, most other popular development
boards, sensors, and components are 5 V devices.
Value Description
RPi.GPIO.PUD_UP Activates the internal pull-up resistor.
RPi.GPIO.PUD_DOWN Activates the internal pull-down resistor.
RPi.GPIO.PUD_OFF Disables the pull-up and pull-down resistors.