Assign multiple outputs (LEDs) using 'for' loop

CircuitPython on hardware including Adafruit's boards, and CircuitPython libraries using Blinka on host computers.

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
User avatar
briandbrady
 
Posts: 21
Joined: Mon Oct 02, 2017 5:00 pm

Assign multiple outputs (LEDs) using 'for' loop

Post by briandbrady »

I want to connect a number of LEDs to outputs (say D2 thru D9). Is there a way to use a loop to assign them? I would like something like the following, but don't know what I can use for where I have "DX". I have tried multiple things and nothing has worked. Maybe this isn't possible with CircuitPython?

For example:

Code: Select all

# assign and configure pins as outputs and put them a list
for i in range(9):
    ledPin[i] = digital.DigitalInOut(board.DX)
    ledPin[i].switch_to_output()

# turn LEDs on/off 1 at a time
for i in range(9):
    ledPins[i].value=True
    time.sleep(1.0)
    ledPins[i].value=False
    time.sleep(0.5)
I can do this in a sketch on an Arduino, but want to make it work using CircuitPython without explicitly typing each pin name in a separate command to assign them.

User avatar
danhalbert
 
Posts: 4686
Joined: Tue Aug 08, 2017 12:37 pm

Re: Assign multiple outputs (LEDs) using 'for' loop

Post by danhalbert »

A more "Pythonic" way of doing what you want to do is to use Python's "list comprehensions", something like

Code: Select all

ledPins = [digitalio.DigitalInOut(pin) for pin in (board.D2, board.D3, board.D4, board.D5)]
for pin in ledPins:
    pin.switch_to_output()

for pin in ledPins:
    pin.Value = True
    time.sleep(1.0)
    pin.value = False
    time.sleep(0.5)
You can use the `eval()` function, but I wouldn't recommend it: it's expensive to execute.

Code: Select all

ledPins = [digitalio.DigitalInOut(pin) for pin in (eval("board.D" + str(pin_num)) for pin_num in range(1, 10))]

User avatar
briandbrady
 
Posts: 21
Joined: Mon Oct 02, 2017 5:00 pm

Re: Assign multiple outputs (LEDs) using 'for' loop

Post by briandbrady »

Thanks. I tried a method similar to the first but must have gotten something wrong. A bit more typing or copy/pasting then my old code, but not bad.

Locked
Please be positive and constructive with your questions and comments.

Return to “Adafruit CircuitPython”