The following gets rid of the error messages:
Code: Select all
# essai de test en aynchrone correspondant à des push button
from machine import Pin
import machine, neopixel, time
# Rajout
import uasyncio as asyncio
from primitives.pushbutton import Pushbutton
##
task = None # Reference to currently running task
# bouton 1 ==> func clear et wait = 0?
pb1 = Pushbutton(Pin(15, Pin.IN))
# bouton 2 ==> func bounce et wait = 70ms
pb2 = Pushbutton(Pin(14, Pin.IN))
# bouton 3 ==> func cycle et wait = 50ms
pb3 = Pushbutton(Pin(12, Pin.IN))
# bouton 4 ==> func rainbow_cycle et wait = 1ms
pb4 = Pushbutton(Pin(13, Pin.IN))
##
# LED strip configuration
# number of pixels
n = 48
# strip control gpio
p = 5
np = neopixel.NeoPixel(machine.Pin(p), n)
## tache principale
async def start(func, var):
global task
if task is not None:
task.cancel()
await asyncio.sleep_ms(0) # Allow cancellation to occur
task = asyncio.create_task(func, var)
# FUNCTIONS FOR LIGHTING EFFECTS
#
# Bouton 1 ==> clear (var) ne sert à rien
async def clear(var):
# turn off all pixels
for i in range(n):
np[i] = (0, 0, 0)
np.write()
# Bouton 2 ==> bounce
async def bounce(wait):
# les couleurs à utiliser
r = 23
g = 210
b = 15
for i in range(2 * n):
for j in range(n):
np[j] = (r, g, b)
if (i // n) % 2 == 0:
np[i % n] = (0, 0, 0)
else:
np[n - 1 - (i % n)] = (0, 0, 0)
np.write()
await asyncio.sleep_ms(wait)
# Bouton 3 ==> cycle
async def cycle(wait):
# les couleurs à utiliser
r = 123
g = 0
b = 154
for i in range(n):
for j in range(n):
np[j] = (0, 0, 0)
np[i % n] = (r, g, b)
np.write()
await asyncio.sleep_ms(wait)
# Bouton 4 ==> rainbow
async def rainbow_cycle(wait):
for j in range(255):
for i in range(n):
rc_index = (i * 256 // n) + j
np[i] = wheel(rc_index & 255)
np.write()
await asyncio.sleep_ms(wait)
# function to go through all colors
async def weel(pos):
# Input a value 0 to 255 to get a color value.
# The colours are a transition r - g - b - back to r.
if pos < 0 or pos > 255:
return (0, 0, 0)
if pos < 85:
return (255 - pos * 3, pos * 3, 0)
if pos < 170:
pos -= 85
return (0, 255 - pos * 3, pos * 3)
pos -= 170
return (pos * 3, 0, 255 - pos * 3)
#await asyncio.sleep_ms(1)
async def main():
pb1.press_func(start, (clear,0,))
pb2.press_func(start, (bounce, 70,))
pb3.press_func(start, (cycle, 50,))
pb4.press_func(start, (rainbow_cycle, 1,))
while True:
await asyncio.sleep(1) # Replace with your code
print('Running')
asyncio.run(main())
In your version you were assigning
press_func routines before they were created. You can't write
because at the time you assign
y to
x,
y doesn't exist. Also you never actually start the scheduler.
My version should load error-free but it won't actually work because I have no idea what
weel is supposed to do.
As a general point, writing a large program all in one go is fine for experienced coders. But if you're learning (or are an experienced programmer learning a new technique) the best way is to start small and simple and gradually add functionality.