Program to dance external LEDs

In Chapter 3, Blinking External LEDs we did a dancing LEDs exercise. We created an illusion light is traveling from one end to the other and from the other end back. Let's write a Python program to achieve the same. Connect seven LEDs with resistors as shown in Chapter 3. Type the following program in Cloud9, save it as dance_LEDs.py and run. You should be able to see light travelling to and fro from both ends.

This is the code for dance_LEDs.py:

#!/usr/bin/python
import Adafruit_BBIO.GPIO as GPIO
from time import sleep

LED_pins = ["P8_7","P8_9","P8_11","P8_13","P8_15","P8_17","P8_19"]

for led in LED_pins:
    GPIO.setup(led,GPIO.OUT)

while True:
    for led in LED_pins:
        GPIO.output(led,GPIO.HIGH)
        sleep(0.1)
        GPIO.output(led,GPIO.LOW)
    for led in reversed(LED_pins):
        GPIO.output(led,GPIO.HIGH)
        sleep(0.1)
        GPIO.output(led,GPIO.LOW)

Explanation

In this program, we have created a list of strings with the name LED_pins. This list has the name of all the GPIO pins that has actual LEDs connected to.

  1. First, we iterated through this list and set the direction of all the pins as output.
  2. Then we ran a while loop for ever. Inside the while loop, we used a for loop to iterate through the list LED_pins. Inside this loop, we turned each pin HIGH for 1 millisecond one by one. So, the actual LEDs glow one by one up to the other end.
  3. After that, in another for loop, we did the same on reversed list of LED_pins. Python has the function reversed(), which reverses elements in a list. Here, we get actual LEDs glowing one by one in a reverse direction.

The above sequence runs until we stop the program manually. If you get any errors, please check the troubleshooting steps in Chapter 3, Blinking External LEDs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.202.240