Hardware Reference
In-Depth Information
In all of the programs in this adventure, I use import RPi.GPIO as GPIO or
import anyio.GPIO as GPIO - this is just like you used before with import
mcpi.minecraft as minecraft . The as tells Python to rename the module
so that it uses the name on the right hand side, and this is helpful when the
module names are very long. It also means that the instructions and programs in
this adventure only have to have one or two lines changed and they will work on
either the Arduino or on the Raspberry Pi. This is a pretty neat feature of Python!
3. Import the module that allows GPIO to be controlled, and define a constant for
the GPIO number that will be connected to your LED, by doing the following:
On the Raspberry Pi:
import RPi.GPIO as GPIO
LED = 15
On the Arduino:
import anyio.GPIO as GPIO
LED = 15
4. Set the GPIO pin numbering mode. (You'll see the letters BCM included in the code
here. For the Raspberry Pi, this stands for “Broadcom”. This is the name of the pro-
cessor chip, and all it means is that you are telling the Raspberry Pi to use the GPIO
numbers rather than the pin numbers on the board.) Now configure the GPIO as an
output so that your program will be able to change the voltage applied to your LED:
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED, GPIO.OUT)
5. Now write a function that will flash the LED once. A parameter t is given to this
function so that later on you can change the speed at which the LED flashes, and
the output() function changes the voltage on the GPIO. When you use True
the voltage will rise to 3.3 Volts, and when you use False the voltage will fall to
0 Volts. This will turn the LED on and off:
def flash(t):
GPIO.output(LED, True)
time.sleep(t)
GPIO.output(LED, False)
time.sleep(t)
6. Write a game loop that flashes the LED, and finally call the GPIO.cleanup()
function when the program finishes, so that the GPIO pins are left in a safe state
at the end. You can read about the try/finally in the Digging into the Code
sidebar later.
 
Search WWH ::




Custom Search