0

The Python code below works perfectly to light 3 LEDs sequentially on a Rasberry Pico; however, I want to use a for loop with part of the object name plus the value of the for loop iterator. If LEDs were added to the board, all that would be needed is a change of the for range(1,x).

Something like the followning does not seem work (Python feels it is getting a value with no properites):

for loop_value in range(1,4):
    #turn LED on, wait, turn LED off
    LED_external_[loop_value].value(1)
    utime.sleep(1)
    LED_external_[loop_value].value(0)

Thanks so much for any input. I feel the function is a convoluted workaround. The for loop would be so much better !!!

########## start (works perfectly, Python coded in Thonny IDE) #######
from machine import Pin
import utime

# assign pin to green LED and initialize to off state
LED_external_1 = machine.Pin(14, machine.Pin.OUT)
LED_external_1.value(0)

# assign pin to yellow LED and initialize to off state
LED_external_2 = machine.Pin(15, machine.Pin.OUT)
LED_external_2.value(0)

# assign pin to red LED and initialize to off state
LED_external_3 = machine.Pin(11, machine.Pin.OUT)
LED_external_3.value(0)

def on_off(LED_Obj_Name):
    #turn LED on, wait, turn LED off
    LED_Obj_Name.value(1)
    utime.sleep(1)
    LED_Obj_Name.value(0)
    
while True:
    on_off(LED_external_1)
    on_off(LED_external_2)
    on_off(LED_external_3)

############################# end ####################################
depperm
  • 10,606
  • 4
  • 43
  • 67
  • 1
    this [question](https://stackoverflow.com/q/8028708/3462319) may have hints about one possible way to solve this. If you assign your variables `LED_external_#` to a list, you could just iterate through them and toggle them. – depperm Sep 15 '21 at 15:51
  • Related, but maybe not a duplicate: [How do I create a variable number of variables](//stackoverflow.com/q/1373164/843953) – Pranav Hosangadi Sep 15 '21 at 17:31

1 Answers1

1

LED_external_[loop_value].value(1) here you're treating LED_external_ as a list. What you can do is add all LEDs to a list and iterate that list.

LED_list = [LED_external_1, LED_external_2, LED_external_3]
for item in LED_list:
    #turn LED on, wait, turn LED off
    item.value(1)
    utime.sleep(1)
    item.value(0)
KavG
  • 169
  • 1
  • 12
  • Thanks. That's works, but I'm trying to get the syntax to use the characters part of an object name in a for loop and append the number part of the object name from the for loop value so Python can do operations on the object during the for loop. My current example is "trivial", but I could see this as being an issue in the future. I didn't want to complicate my question, but, sending the number at the end of the object name to a function that has the characters part of the object name, and Python similarly doesn't recognize the name as an object name within the function. – realtime upload Sep 15 '21 at 16:37