Timebase for Everything: Ticker Real-Time

I covered the basics for making an embedded project which is also portable in the previous post Part1. Now it’s time to go one step further and implement a portable Ticker (a.k.a. system tick timer) for Porty. It will be the timebase of the system and may come in handy for basic time scheduling.

Features of the Ticker

Ticker is designed to be used with Porty and it has 2 use-cases. First, Ticker counts time in means of “ticks” which means the smallest time unit; second, it calls user functions in its interrupt that gives us a possibility to extend the usage. More importantly, it has to be totally MCU independent and can be used with any microcontroller wether or not it has a built-in SysTick functionality.

The mighty Ticker function runs in an interrupt (elevated) with a predefined period. The period is ideally 1ms and can be smaller when the MCU supports. The sub-millisecond part is defined in settings.h file.

Project files

I separated the code in 2, ticker.c  and ticker_hw.c in order to make it portable. The ticker_hw.c file initializes a hardware timer, which can also be SysTick in ARM, and runs the ISR routine in the real interrupt. Here TIM4 of STM32F100 is used for demonstration but the attached project also uses SysTick.

Note that the interrupt priority is set in board.h  file.

The simple header ticker_hw.h  is given below.

The real abstraction takes place in ticker.c  file. A fake ISR routine counts time in milliseconds as well as ticks and records into tTickerTime  struct.

Interface functions TickerRead_ms() and TickerRead_ticks() returns the time as milliseconds or ticks.

The header ticker.h  implements 2 hook functions,  mTickerHook_ms() and  mTickerHook_fast(), that will be called on every tick or every millisecond.

Finally, we can replace our blinking delay function in main.c  with a more precise one.

Now you can observe a perfect 1Hz blink on the Green LED of the Discovery board 😀


Download link of the full project is here: Porty-0.1.1-Ticker (using TIM4 Porty-0.1.1-Ticker-TIM4).

For compilation check here.