Raspberry Pi A User Manual page 247

Hide thumbs Also See for Raspberry Pi A:
Table of Contents

Advertisement

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
(as described in Chapter 12, "An Introduction to Python") and set it to the
input_value
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
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
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)
C H A P T E R 1 4
T H E G P I O P O R T
and the second
while
instruction to get feedback:
print
, an embedded loop—are
input_value
231

Hide quick links:

Advertisement

Table of Contents
loading

Related Products for Raspberry Pi Raspberry Pi A

This manual is also suitable for:

Raspberry pi b

Table of Contents