Operation Manual

it blink. First, add the following line to create an infinite loop in the program:
while True:
Next, add the following lines to switch the pin on, wait 2 seconds, and then switch it off again before waiting another 2 seconds.
Make sure each line starts with four spaces, to signify that it is part of the infinite while loop:
GPIO.output(11, True)
time.sleep(2)
GPIO.output(11, False)
time.sleep(2)
The finished program should look like this (see Figure 12-4):
import RPi.GPIO as GPIO
import time
GPIO.setup(11, GPIO.OUT)
while True:
GPIO.output(11, True)
time.sleep(2)
GPIO.output(11, False)
time.sleep(2)
Figure 12-4: The gpiooutput.py program, being edited in nano, and waiting for its final line
Save the file as gpiooutput.py. If youre using a Python development environment such as SPE, dont try to run the program
from within the editor. Most Raspberry Pi Linux distributions restrict the use of the GPIO port to the root user, so the program
will need to be run using the command sudo python gpiooutput.py at the terminal to get it started. If all has gone well, you
should see the LED begin to blink on and off at regular intervals—and youve created your first home-made output device for
the Pi.
If things dont work, dont panic. First, check all your connections. The holes in a breadboard are quite small, and its easy to
think youve inserted a component into one row only to find its actually in another. Next, check that youve connected the circuit
to the right pins on the GPIO portwith no labelling on the Pi itself, mistakes are unfortunately easy to make. Finally, double-
check your components—if the forward voltage of your LED is higher than 3.3 V or if your current limiting resistor is too large,
the LED wont light up.
Although this example is basic, its a good demonstration of some fundamental concepts. To extend its functionality, the LED
could be replaced with a buzzer to make an audible alert, or a servo or motor as part of a robotics platform. The code used to
activate and deactivate the GPIO pin can be integrated into other programs, causing an LED to come on when new email arrives
or a flag to be raised when a friend has joined an IRC channel.
GPIO Input: Reading a Button
Being able to use the GPIO as an output is undeniably useful, but it becomes significantly more so when you can combine that