Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

As mentioned earlier this hour, to confuse things, there are two ways to reference the GPIO signals in
the option placeholder:


Using the pin number on the GPIO interface
Using the GPIO signal number from the Broadcom chip

The GPIO.BOARD option, which you use like this, tells the library to reference signals based on the
pin number on the GPIO interface:


GPIO.setmode(GPIO.BOARD)

The other option is to use the Broadcom chip signal number, specified by the GPIO.BCM value, as
shown here:


GPIO.setmode(GPIO.BCM)

For example, GPIO signal 18 is on pin 12 of the GPIO interface. If you use the GPIO.BCM mode, you
reference it using the number 18 , but if you use the GPIO.BOARD mode, you reference it using the
number 12.


This hour uses GPIO.BCM mode because it’s easier to see in both the Pi Cobbler and the Gertboard.


After you select the mode, you must define which GPIO signals to use in your program and whether
they will be used for input or output. You do that with the setup() method, as shown in the
following syntax:


Click here to view code image


GPIO.setup(channel, direction)

For the direction parameter, you can use constants defined in the library: GPIO.IN and GPIO.OUT.
For example, to set GPIO signal 18 to use for output, you’d write this:


GPIO.setup(18, GPIO.OUT)

Now the GPIO 18 signal is ready to use for output from your Python program. The next step is to
actually control what you output.


Controlling GPIO Output


The GPIO pins allow you to send a digital output signal to an external device. The following sections
walk through how to control the output signal from your Python program.


Setting Up the Hardware to View the GPIO Output


Before you can dive into coding, you need to set up the hardware environment for the project. You
can use either the Pi Cobbler breakout box with your own components or the Gertboard, which
contains all the components you’ll need for the project. The following sections show the instructions
for both methods.


Setting Up the Pi Cobbler for Output


Unfortunately, to use the Pi Cobbler for this project, you need to collect a few more pieces of
hardware:


A breadboard
A 1,000-ohm resistor
Free download pdf