zaord
zaord

Reputation: 13

uasyncio parralel (multi)threading seems to not work

I try to use two routine I wants to be executed in the same time continuously, but Only the first one is running...

Where am I wrong ?

 async def screen(self): #first routine
    Writer.set_textpos(ssd, 0, 0)  # In case previous tests have altered it
    wri = Writer(ssd, small, verbose=False)
    wri.set_clip(False, False, False)

    ...
        refresh(ssd)
        utime.sleep_ms(200)
    
async def InvPress(self):  #second routine
    utime.sleep_ms(1000)
    print('Sw2',self.SW2.value())
    while True:
        print(self.SW2.value())
        if self.SW2.value():
            if self.PressPos == 1:
                self.stepper.steps(-1600,2600)
                self.PressPos = not self.PressPos
            else :
                self.stepper.steps(+1600,2600)
                self.PressPos = not self.PressPos
        utime.sleep_ms(120)


async def main(self): #this don't work in parallel (only the first routine is running)
    uasyncio.create_task(self.InvPress())
    uasyncio.create_task(self.screen())       
    await uasyncio.sleep(10)

Upvotes: 0

Views: 278

Answers (1)

VPfB
VPfB

Reputation: 17342

(Disclaimer: Don't know the micropython)

Asynchronous programs are based on the so called coopeative scheduling. Coroutines/tasks can be switched only at certain points. Those points are the awaits in the code.

If there is no await in a coroutine, no tasks switch is possible, i.e. no other coroutine has a chance to run. That is the case of InvPress. (The other coroutine is not fully listed)

Closely related is the rule, that a regular sleep in an async program is a mistake. It does nothing except the sleep and prevents other coroutines to run in that time. During such sleep is the program simply dead (unresponsive). If a delay is needed, always await the proper asynchronous sleep routine.

Upvotes: 1

Related Questions