Skip to content

TimerService

Daniel Johnson edited this page Jul 9, 2021 · 24 revisions
  1. Introduction
  2. Function Descriptions
      General Functions
      Scheduling Functions
  3. Examples
      Blink LED

1. Introduction

The TimerService is a task scheduler that allows for multiple callbacks to be scheduled on a single timer compare register.

2. Function Descriptions

General Functions

uint32_t GetTick()

Returns the current tick of the timer. All timers are treated as 32 bit timers. This is a virtual function passed down to the underlying abstraction. See Building a New Abstraction for how to achieve this with lower resolution timers.

uint32_t GetTicksPerSecond()

Returns the speed of the timer in number of ticks per second. This is a virtual function passed down to the underlying abstraction.

Scheduling Functions

By default, Tasks are not allowed to be scheduled during a callBack. If this is required, add #define ALLOW_TASK_TO_SCHEDULE_IN_CALLBACK

void ScheduleCallBack(std::function<void()> callBack, uint32_t tick)

This schedules a callBack to be executed at the input tick. This is for scheduling an infrequent callBack. This will not update a previously scheduled callBack. The callBack is not able to be unscheduled.

void ScheduleTask(Task *task, uint32_t tick)

This schedules a task to be executed at the input tick. This is for scheduling more frequent tasks. This will also update the task execute tick if the task is already scheduled.

void UnScheduleTask(Task *task)

This unschedules a task that was previously scheduled.

3. Examples

Blink LED

Declaration and CallBack Function

ITimerService *_timerService;
IDigitalService *_digitalService;
bool val = false;
void toggleLED()
{
     // set LED pin to val
    _digitalService->WritePin(45, val); //PC13
     // toggle val
    val = !val;
}
Task toggleLEDTask = Task(&toggleLED);

Setup

 // Initialize LED pin
_digitalService->InitPin(45, PinDirection::Out); //PC13 as Output
 // Setup first execution of task to be now + 1 second
_timerService->ScheduleTask(&toggleLEDTask, _timerService->GetTick() + _timerService->GetTicksPerSecond());

Loop

 // if the task has been executed and is no longer scheduled, 
 // reschedule the task for 1 second after the previous scheduled time.
if(!toggleLEDTask.Scheduled)
    _timerService->ScheduleTask(&toggleLEDTask, toggleLEDTask.Tick + _timerService->GetTicksPerSecond());