1.6. timer — Timers

Timers are started with a timeout, and when the time is up the timer expires and the timer callback function is called from interrupt context.

The timeout resolution is the system tick period. Timeouts are always rounded up to the closest system tick. That is, a timer can never expire early, but may expire slightly late.

An application requiring timers with higher precision than the system tick must use the hardware timers.


Source code: src/kernel/timer.h, src/kernel/timer.c

Test code: tst/kernel/timer/main.c

Test coverage: src/kernel/timer.c


Defines

TIMER_PERIODIC

Typedefs

typedef void (*timer_callback_t)(void *arg_p)

Time callback prototype.

Functions

int timer_module_init(void)

Initialize the timer module. This function must be called before calling any other function in this module.

The module will only be initialized once even if this function is called multiple times.

Return
zero(0) or negative error code.

int timer_init(struct timer_t *self_p, const struct time_t *timeout_p, timer_callback_t callback, void *arg_p, int flags)

Initialize given timer object with given timeout and expiry callback. The timer resolution directly depends on the system tick frequency and is rounded up to the closest possible value. This applies to both single shot and periodic timers.

Return
zero(0) or negative error code.
Parameters
  • self_p: Timer object to initialize with given parameters.
  • timeout_p: The timer timeout value.
  • callback: Functaion called when the timer expires. Called from interrupt context.
  • arg_p: Function callback argument. Passed to the callback when the timer expires.
  • flags: Set TIMER_PERIODIC for periodic timer.

int timer_start(struct timer_t *self_p)

Start given initialized timer object.

Return
zero(0) or negative error code.
Parameters
  • self_p: Timer object to start.

int timer_start_isr(struct timer_t *self_p)

See timer_start() for a description.

This function may only be called from an isr or with the system lock taken (see sys_lock()).

int timer_stop(struct timer_t *self_p)

Stop given timer object. This has no effect on a timer that already expired or was never started. A stopped timer may be restarted with the initial timeout by calling timer_start().

Return
true(1) if the timer was stopped, false(0) if the timer already expired or was never started, and otherwise negative error code.
Parameters
  • self_p: Timer object to stop.

int timer_stop_isr(struct timer_t *self_p)

See timer_stop() for description.

This function may only be called from an isr or with the system lock taken (see sys_lock()).

struct timer_t

Public Members

struct timer_t *next_p
sys_tick_t delta
sys_tick_t timeout
int flags
timer_callback_t callback
void *arg_p