avr-task-scheduler

AVR mcu bare metal task scheduler
Index Commits Files Refs README LICENSE
src/scheduler.c (1158B)
   1 #include "scheduler.h"
   2 
   3 #ifdef __cplusplus
   4 extern "C" {
   5 #endif
   6 
   7 typedef struct {
   8     uint8_t task_cnt, update_cnt;
   9     task_t *tasks;
  10 } scheduler_t;
  11 
  12 static scheduler_t scheduler = {0};
  13 
  14 void scheduler_init(task_t *tasks, uint8_t task_count) {
  15     scheduler.tasks = tasks;
  16     scheduler.task_cnt = task_count;
  17 }
  18 
  19 void scheduler_tick(void) {
  20     scheduler.update_cnt += (scheduler.update_cnt == 255 ? 0 : 1);
  21 }
  22 
  23 // update every 1 ms
  24 void scheduler_update(void) {
  25     if (scheduler.update_cnt == 0) {
  26         return;
  27     }
  28 
  29     scheduler.update_cnt--;
  30 
  31     for (uint8_t i = 0; i < scheduler.task_cnt; ++i) {
  32         if (scheduler.tasks[i].ticks > 1) {
  33             scheduler.tasks[i].ticks--;
  34             continue;
  35         }
  36 
  37         scheduler.tasks[i].ticks = scheduler.tasks[i].period;
  38         scheduler.tasks[i].on_update();
  39     }
  40 }
  41 
  42 void scheduler_set_task_period(uint8_t task_id, uint16_t new_period) {
  43     for (uint8_t i = 0; i < scheduler.task_cnt; ++i) {
  44         if (scheduler.tasks[i].id == task_id) {
  45             scheduler.tasks[i].period = new_period;
  46             scheduler.tasks[i].ticks = new_period;
  47         }
  48     }
  49 }
  50 
  51 #ifdef __cplusplus
  52 }
  53 #endif