20. PikaStdTask multitasking

The PikaStdTask multitasking library provides asynchronous multitasking capabilities of Task (task loop).

20.1. Install

  1. Add the dependency of PikaStdLib to requestment.txt. The version number of PikaStdLib should be the same as the version number of the kernel.
  1. PikaStdLib==v1.6.1
  1. Run pikaPackage.exe

20.2. class Task():

The Task class provides the task loop function, and a task loop can be created by creating an object of the Task class.

20.2.1. Methods of the Task class

  1. from PikaObj import *
  2. import PikaStdData
  3. class Task(TinyObj):
  4. calls = PikaStdData.List()
  5. def __init__(self):
  6. pass
  7. # regist a function to be called always
  8. def call_always(self, fun_todo: any):
  9. pass
  10. # regist a function to be called when fun_when() return 'True'
  11. def call_when(self, fun_todo: any, fun_when: any):
  12. pass
  13. # register a function to be called periodically
  14. def call_period_ms(self, fun_todo: any, period_ms: int):
  15. pass
  16. # run all registered function once
  17. def run_once(self):
  18. pass
  19. # run all registered function forever
  20. def run_forever(self):
  21. pass
  22. # run all registered function until time is up
  23. def run_until_ms(self, until_ms: int):
  24. pass
  25. # need be overried to supply the system tick
  26. def platformGetTick(self):
  27. pass

20.2.2. Instructions:

  1. Use the call_xxx() method to specify the calling method, and register the function to be executed in the task object.

  2. Use the run_xxx() methods to specify how the task loops and execute all functions in the task object.

  3. Time-related functions, such as call_period_ms() and run_until_ms(), need to provide the system clock by creating a new class that inherits from PikaStdTask, and then override the platformGetTick() method.

20.2.3. Notice:

  1. All registered functions should be non-blocking, otherwise the entire task loop will be blocked.

  2. The task loop is not real-time.

20.2.4. Example:

  1. Create a new class that inherits from PikaStdTask.
  1. # STM32G0.py
  2. class Task(PikaStdTask.Task):
  3. # override
  4. def platformGetTick():
  5. pass
  1. Override the platformGetTick() method.
  1. /* STM32G0_Task.c */
  2. void STM32G0_Task_platformGetTick(PikaObj* self) {
  3. obj_setInt(self, "tick", HAL_GetTick());
  4. }
  1. Python use cases
  1. import STM32G0
  2. import PikaPiZero
  3. import PikaStdLib
  4. pin = STM32G0.GPIO()
  5. rgb = PikaPiZero.RGB()
  6. mem = PikaStdLib.MemChecker()
  7. pin.setPin('PA8')
  8. pin.setMode('out')
  9. pin.enalbe()
  10. rgb.init()
  11. rgb.enable()
  12. print('task demo')
  13. print('mem used max:')
  14. mem.max()
  15. def rgb_task():
  16. rgb.flow()
  17. def led_task():
  18. if pin.read():
  19. pin.low()
  20. else:
  21. pin.high()
  22. task = STM32G0.Task()
  23. task.call_period_ms(rgb_task, 50)
  24. task.call_period_ms(led_task, 500)
  25. task.run_forever()