Replies: 2 comments 11 replies
-
One way to do it is this (but it introduces a lot of concepts you might not be familiar with yet. zip is standard python & cycle is similar to standard python itertools.cycle, so you can read up about it if you're inclined. # Similar to itertools.cycle: Repeatedly yield each value in the sequence. (Does not work for generators)
def cycle(seq):
while True:
yield from seq
# Make a sequence of leds for zip to use
leds = [led_1, led_2, led_3]
for values in cycle(state):
# (Pair each item in leds with the corresponding item in values)
for led, value in zip(leds, values):
led.value(value)
time.sleep(1) Otherwise, if you want to keep track of the sequence position i = 0
while True:
# Assign led values based on state[i][j] as in your code, then update the index value as follows:
i = (i + 1) % len(state) Modulo arithmetic with (Note: I didn't test this code, so there may be errors, subtle or obvious) |
Beta Was this translation helpful? Give feedback.
-
Next step is to make it running concurrently with asyncio. import asyncio
class LED:
"""
Mock class to test without hardware
"""
def __init__(self, pin):
self.pin = pin
def value(self, state):
if state:
print(f"LED {self.pin} on")
else:
print(f"LED {self.pin} off")
async def led_task(leds, values):
while True:
for *led_values, sleep_time in values:
for led, value in zip(leds, led_values):
led.value(value)
await asyncio.sleep(sleep_time)
print()
async def ping():
while True:
await asyncio.sleep(5)
print("Ping")
async def main():
leds = (LED(1), LED(2), LED(3))
state=[
[1,0,0,5],
[0,1,0,2],
[0,0,1,1],
[0,0,1,5],
]
task1 = asyncio.create_task(led_task(leds, state))
task2 = asyncio.create_task(ping())
print("Waiting 20 seconds")
await asyncio.sleep(20)
if __name__ == "__main__":
asyncio.run(main()) |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi,
I have a small project (with ESP32) that needs to modify three output pins with values that change over time.
I'd like to put these values (0 and 1) in an array and be able to assign them to my outputs.
But I don't know how to go about it.
I tried a double for loop but it doesn't work
It should look something like this:
'''
from machine import Pin
led_1 = Pin(23,Pin.OUT,Pin.PULL_DOWN, value=0)
led_2 = Pin(22,Pin.OUT,Pin.PULL_DOWN, value=0)
led_3 = Pin(21,Pin.OUT,Pin.PULL_DOWN, value=0)
state=[
[1,0,1],
[0,1,1],
[0,0,1],
[1,1,0],
[0,1,0],
[0,0,1]
]
while True:
led_1.value(state[i][j]) # value 1 then 0 then 0 ...
led_2.value....# value 0 then 1 then 0...
led_3.value.....# value 1 then 1 then 1...
time.sleep(1)
'''
Do you have any ideas how to do this?
Thanks in advance.
Beta Was this translation helpful? Give feedback.
All reactions