Hardware Reference
In-Depth Information
Before you can use the GPIO library you installed earlier in this chapter, you'll need to import
it into your Python project. Accordingly, start the ile with the following line:
import RPi.GPIO as GPIO
Remember that Python is case-sensitive, so be sure to type RPi.GPIO exactly as it appears.
To allow Python to understand the concept of time (in other words, to make the LED blink,
rather than just turning it on and of), you'll also need to import the time module. Add the
following line to the project:
import time
With the libraries imported, it's time to address the GPIO ports. he GPIO library makes it
easy to address the general-purpose ports through the instructions GPIO.output and
GPIO.input , but before you can use them, you'll need to initialise the pins as either inputs
or outputs. In this example, Pin 11 is an output, so add the following line to the project:
GPIO.setup(11, GPIO.OUT)
his tells the GPIO library that Pin 11 on the Raspberry Pi's GPIO port should be set up as an
output. If you were controlling additional devices, you could add more GPIO.setup lines
into the project. For now, however, one will suice.
With the pin conigured as an output, you can switch its 3.3 V supply on and of in a simple
demonstration of binary logic. he instruction GPIO.output(11, True) will turn the pin
on, while GPIO.output(11, False) switches it of again. he pin will remember its last
state, so if you only give the command to turn the pin on and then exit your Python pro-
gram, the pin will remain on until told otherwise.
Although you could just add GPIO.output(11, True) to the Python project to switch the
pin on, it's more interesting to make it blink. First, add the following line to create an ininite
loop in the program:
while True:
Search WWH ::




Custom Search