for loop won't work with list of class objects

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
smhodge
Posts: 86
Joined: Tue Jan 22, 2019 2:16 am
Location: Kirkland, WA, USA

for loop won't work with list of class objects

Post by smhodge » Tue Oct 08, 2019 10:49 pm

    I can't understand why the following code won't work. I first create a class for pyBoard internal led's and then create 2 instances, <led1> and <led2>. Each led object has a method to count timer ticks and then toggle the led when the count reaches a trigger value, then reset the count to 0. The function <FlashLeds()> loops over all the led objects to do this. It works if I call the methods directly but does not work if I use a for loop. See ****************** below.

    What am I missing here? Thanks, Steve
    ------------------------------------

    # Flash3.py
    # import pyb # Done by <boot.py>

    class IntLed(pyb.LED): # Internal led's on pyBoard

    def __init__(self, id, trig=8):
    super().__init__(id)
    self.trig=trig
    self.cntr=0

    def flashLed(self): # Flash led when <cntr> = <trig>, then reset <cntr> to 0, <cntr> increments every 250 ms
    self.cntr += 1
    if self.cntr == self.trig:
    self.toggle()
    self.cntr = 0

    led1=IntLed(1) # Make two instances of internal led's (ignore the other 2 for now)
    led2=IntLed(2, trig=4)

    leds= [led1, led2] # List of internal led's

    def flashLeds():
    for led in leds: # ********** This for loop, using the list, does not work
    led.flashled()
    # led1.flashLed() # ********** but calling them individually (with no for loop) does!
    # led2.flashLed()

    tmr = pyb.Timer(1) # Timer instance, use timer #1
    tmr.init(freq=4) # 4 Hz --> interrupt every 250 ms
    tmr.callback(lambda t:flashLeds())

    User avatar
    dhylands
    Posts: 3821
    Joined: Mon Jan 06, 2014 6:08 pm
    Location: Peachland, BC, Canada
    Contact:

    Re: for loop won't work with list of class objects

    Post by dhylands » Tue Oct 08, 2019 10:55 pm

    You're not calling the same method in the for loop as you are when you do it manually. You're calling flashled in the for loop and flashLed when doing it manually (note the capital L in flashLed).

    smhodge
    Posts: 86
    Joined: Tue Jan 22, 2019 2:16 am
    Location: Kirkland, WA, USA

    Re: for loop won't work with list of class objects

    Post by smhodge » Tue Oct 08, 2019 11:33 pm

    Duh. Thanks.

    Post Reply