for pin in ledPins:
GPIO.setup(pin, GPIO. OUT) # Set all ledPins' mode is output
GPIO.output(pin, GPIO. HIGH) # Set all ledPins to high(+3.3V) to off led
def loop():
w hile Tr ue:
for pin in ledPins: #make led on from left to right
GPIO.output(pin, GPIO.LOW)
time.sleep(0.1)
GPIO.output(pin, GPIO.HIGH)
for pin in ledPins[::-1]: #make led on from right to left
GPIO.output(pin, GPIO.LOW)
time.sleep(0.1)
GPIO.output(pin, GPIO.HIGH)
def destroy():
for pin in ledPins:
GPIO.output(pin, GPIO. HIGH) # turn off all leds
GPIO. cleanup() # Release resource
if __name__ == '__main__': # Program start from here
setup()
try:
loop()
e xcept KeyboardInterrupt: # When 'Ctrl+C' is pressed, the subprogram destroy() will
be executed.
destroy()
In the program, first define 10 pins connected to LED, and set them to output mode in subfunction setup().
Then in the loop() function, use two āforā cycles to realize flowing water light from right to left and from left
to right. Among them, ledPins[::-1] is used to traverse elements of ledPins in reverse order.
def loop():
w hile Tr ue:
for pin in ledPins: #make led on from left to right
GPIO.output(pin, GPIO.LOW)
time.sleep(0.1)
GPIO.output(pin, GPIO.HIGH)
for pin in ledPins[::-1]: #make led on from right to left
GPIO.output(pin, GPIO.LOW)
time.sleep(0.1)
GPIO.output(pin, GPIO.HIGH)