Hardware Reference
In-Depth Information
he circuit you just built creates a situation whereby the input pin, which in this instance is Pin
12 of the Raspberry Pi's GPIO port, is constantly high thanks to the pull-up resistor connected
to a 3.3 V supply. When the push-button is pressed, the circuit is grounded and becomes low ,
providing the cue for your Python program to know that the button has been activated.
You may wonder why the resistor is required at all, and why the switch does not simply con-
nect Pin 12 to Pin 6 or Pin 1 directly. While this is possible, it creates what is known as a
loating pin, which is a pin that doesn't know whether it's high or low. As a result, the circuit
will act as though the button is being pressed even when it isn't, and may fail to detect the
button being pressed even when it is.
Open a new Python ile, either in a text editor or using one of the Python integrated develop-
ment environments (IDEs) available on the Raspberry Pi. To begin, you will need to import
the same GPIO library as in the previous GPIO output example:
import RPi.GPIO as GPIO
You don't need to import the time library, because this example doesn't need any timing instruc-
tions. Instead, you can get right to setting up Pin 12 as an input. his is done in the same way as
setting a pin as an output, with just the inal part of the instruction changed accordingly:
GPIO.setup(12, GPIO.IN)
If you're not using Pin 12 for this, make sure you change the pin number in the preceding
instruction.
As with the previous example, the next step is to create an ininite loop that constantly
checks the input pin to see if it's been brought low (in other words, if it's been pressed). Begin
the loop with the following code line:
while True:
Reading the status of an input pin is very similar to setting the status of an output pin, with
one exception: before you can do anything useful with the resulting value, you'll need to store
it in a variable. he following instruction tells Python to create a new variable called input_
value (as described in Chapter 11, “An Introduction to Python”) and set it to the current value
of Pin 12:
input_value = GPIO.input(12)
Search WWH ::




Custom Search