|
Look at the following example code:
What do you think it will do? “from LEDs import *” opens a file called LEDs.py which does some work behind the scenes and give you access to a function called LED(). Hit F5 or [Run] -> [Run Module] to start the program. Hit “ctrl-C” to stop.
Why does the light continue to blink? Does the indentation matter or is it just for looks?
Python has an interactive window which is very helpful. After running the program once, type help(LED) to see it’s description:
What if you just wanted it to blink five times? Try the following code in the interactive window to see what it does:
>>>for x in range(5):
print “x =” , x
Adapt this code to make the LED blink a limited number of times.
If you are curious, open LEDs.py (see below) to see what is hidden in the module!
Learn more and download at: http://www.python.org
Search Maker's Box for Python
# LEDs.py
#import RPi.GPIO as GPIO
import time
import sys
#GPIO.setwarnings(False)
#GPIO.setmode(GPIO.BOARD)
for pin in [11, 12, 13]:
pass
#GPIO.setup(pin, GPIO.OUT)
def LED(pin, state):
'''Turns LED on (True) or off (False).'''
if state not in [True, False]:
print "Only correct state for LED is:\n"
print " True or False\n"
sys.exit()
if state:
#GPIO.output(pin, GPIO.HIGH)
print pin, " HIGH"
else:
print pin, " LOW"
#GPIO.output(pin, GPIO.LOW)
if __name__ == "__main__":
for i in range(5):
for pin in [11, 12, 13]:
LED(pin, True)
time.sleep(1)
LED(pin, False)
#GPIO.cleanup()
-----------------------------
# stoplight.py
from time import sleep
from LEDs import *
green = 11
yellow = 12
red = 13
ON = True
OFF = False
while True:
LED(green, ON)
time.sleep(2)
LED(green, OFF)
sleep(2)
No comments:
Post a Comment