5.4. PikaStdTask multitasking

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

5.4.1. Install

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.10.0

Run pikaPackage.exe

5.4.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.

5.4.2.1. Methods of the Task class

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

5.4.2.2. Instructions:

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

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

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.

5.4.2.3. Notice:

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

The task loop is not real-time.

5.4.2.4. Example:

Create a new class that inherits from PikaStdTask.

  1. # STM32G0.py
  2. class Task(PikaStdTask.Task):
  3. # override
  4. def platformGetTick():
  5. pass

Override the platformGetTick() method.

  1. /* STM32G0_Task.c */
  2. void STM32G0_Task_platformGetTick(PikaObj* self) {
  3. obj_setInt(self, "tick", HAL_GetTick());
  4. }

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()