Hardware Reference
In-Depth Information
As with the previous example, the next step is to create an infinite 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. The following instruction tells Python to create a new variable called
input_value (as described in Chapter 12, “An Introduction to Python”) and set it to the
current value of Pin 12:
input_value = GPIO.input(12)
Although the program could be executed now and work, it doesn't do anything useful. To
make sure you know what's going on, add the following print instruction to get feedback:
if input_value == False:
print(“The button has been pressed.”)
while input_value == False:
input_value = GPIO.input(12)
The last two lines—the second while and the second input_value , an embedded loop —are
important. Even on the Raspberry Pi's processor, which is relatively underpowered when
compared to high-performance desktop and laptop processors, Python runs very quickly.
This embedded loop tells Python to keep checking the status of Pin 12 until it's no longer
low, at which point it knows the button has been released. Without this loop, the program
will loop while the button is being pressed—and no matter how quick your reflexes, you'll
see the message printed to the screen multiple times, which is misleading.
The final program should look like this:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.IN)
while True:
input_value = GPIO.input(12)
if input_value == False:
print(“The button has been pressed.”)
while input_value == False:
input_value = GPIO.input(12)
Search WWH ::




Custom Search