MicroPython exercise implement class to do repeat task in fix-time delay, without blocking.

In MicroPython, for convenience, we usually call time.sleep() to implement fix-time delay. But time.sleep() is blocking function, means it will not return until sleep time reached and block other opeeration.

This exercise implement class to do repeat task in fix-time delay, without blocking. The code measure ticks difference between current time and expected time to determine is it time reached. It not, return control to next job. Such that you can do others while it's waiting.


Tested on NodeMCU ESP-C3-32S-Kit running MicroPython v1.19.1.

mpy_NodeMCU_ESPC3_delay_nosleep.py
"""
MicroPython exercise
implement class to do repeat task in fix delay,
without blocking.

Tested on NodeMCU ESP-C3-32S-Kit

ref:
MicroPython time module:
https://docs.micropython.org/en/latest/library/time.html
"""
import os
import sys
import time

print()

print("====================================")
print(sys.implementation[0], os.uname()[3],
      "\nrun on", os.uname()[4])
print("====================================")
time.sleep(1)

class taskRepeat_class:
    Tick_Dur = 2000  # delay 2000ms

    def __init__(self):
        self.prvTime = time.ticks_ms()
        self.nextTick = time.ticks_add(self.prvTime, self.Tick_Dur)
        
    def prc(self):
        curTime = time.ticks_ms()
        if (time.ticks_diff(curTime, self.nextTick ) > 0):
            # do anything in fixed duration
            print("reach\t", time.ticks_diff(curTime, self.prvTime),"ms")
            self.nextTick = time.ticks_add(curTime, self.Tick_Dur)
            self.prvTime = curTime
        else:
            # time not reached
            print(".", end="")

myTask = taskRepeat_class()

while True:
    myTask.prc()
    time.sleep(0.1) # time.sleep() is a blocking function
                    # it willnot return before sleep time reached.
    

remark:
values returned by ticks_ms(), etc. functions may wrap around, so directly using subtraction on them will produce incorrect result. That is why ticks_diff() is needed, it implements modular (or more specifically, ring) arithmetics to produce correct result even for wrap-around values.

ref: MicroPython time module

more:
MicroPython run tasks concurrently, base on time ticks, uasyncio and _thread.

Comments

Popular posts from this blog

480x320 TFT/ILI9488 SPI wih EP32C3 (arduino-esp32) using Arduino_GFX Library

MicroPython/ESP32-C3 + 1.8" 128x160 TFT ST7735 SPI, using boochow/MicroPython-ST7735 library.