0

How can I write code to allow function run in background in exactly that time that I need? When I run this func in cycle it's executing after others.

import time
from machine import Pin

a_1 = Pin(21, Pin.OUT)
a_2 = Pin(20, Pin.OUT)

def do_something(x):
    print(x)

def some_other_actions():
    time.sleep(10)

def calc_one_two():
    return 1, 2

def func(a, b, on_tmr=2, off_tmr=1):

    a_1.on()
    do_something(a)
    time.sleep_ms(on_tmr)  # sleep for 2ms
    a_1.off()
    time.sleep_ms(off_tmr)  # sleep for 1ms

    a_2.on()
    do_something(b)
    time.sleep_ms(on_tmr)  # sleep for 2ms
    a_2.off()
    time.sleep_ms(off_tmr)  # sleep for 1ms

while True:
    one, two = calc_one_two()
    func(one, two)
    some_other_actions()  # actions that need some time

0livaw
  • 1

1 Answers1

0

uasyncio is what you should look for. Look at documentation here https://docs.micropython.org/en/latest/library/uasyncio.html Bellow is minimal sample for blinking leds asynchronously, exactly what you are doing

import uasyncio

async def blink(led, period_ms):
    while True:
        led.on()
        await uasyncio.sleep_ms(5)
        led.off()
        await uasyncio.sleep_ms(period_ms)

async def main(led1, led2):
    uasyncio.create_task(blink(led1, 700))
    uasyncio.create_task(blink(led2, 400))
    await uasyncio.sleep_ms(10_000)


# Running on a generic board
from machine import Pin
uasyncio.run(main(Pin(21), Pin(20)))
Lixas
  • 6,938
  • 2
  • 25
  • 42