Hardware Reference
In-Depth Information
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)
he 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.
his 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 relexes, you'll
see the message printed to the screen multiple times, which is misleading.
he inal program should look like this:
import RPi.GPIO as GPIO
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)
Save the ile as gpioinput.py , and then execute it from the terminal with sudo python
gpioinput.py . At irst, nothing will happen—but if you press the push-button switch, the
program will print the message from line six to the terminal (see Figure 12-6). Release the
button and press it again, and the message will be repeated.
As with the previous input example, this is a deceptively simple program that can be used for
many purposes. In addition to being able to read when a switch is pressed, the same code can
be used to read when the pins of a separate device—such as a sensor or external microcon-
troller—have been pulled high or low.
Search WWH ::




Custom Search