µC/OS-III provides timer services to the application programmer and code to handle timers is found in os_tmr.c
. Timer services are enabled when setting OS_CFG_TMR_EN
to 1 in os_cfg.h
.
Timers are down counters that perform an action when the counter reaches zero. The user provides the action through a callback function (or simply callback). A callback is a user-declared function that will be called when the timer expires. The callback can be used to turn a light on or off, start a motor, or perform other actions. However, it is important to never make blocking calls within a callback function (i.e., call OSTimeDly()
, OSTimeDlyHMSM()
, OS???Pend()
, or anything that causes the timer task to block or be deleted).
Timers are useful in protocol stacks (retransmission timers, for example), and can also be used to poll I/O devices at predefined intervals.
An application can have any number of timers (limited only by the amount of RAM available). Timer services (i.e. functions) in µC/OS-III start with the OSTmr???()
prefix, and the services available to the application programmer are described in µC/OS-III API Reference.
The resolution of all the timers managed by µC/OS-III is determined by the configuration constant: OS_CFG_TMR_TASK_RATE_HZ
, which is expressed in Hertz (Hz). So, if the timer task (described later) rate is set to 10, all timers have a resolution of 1/10th of a second (ticks in the diagrams to follow). In fact, this is the typical recommended value for the timer task. Timers are to be used with “coarse” granularity.
µC/OS-III provides a number of services to manage timers as summarized in the table below.
A timer needs to be created before it can be used. You create a timer by calling OSTmrCreate()
and specify a number of arguments to this function based on how the timer is to operate. Once the timer operation is specified, its operating mode cannot be changed unless the timer is deleted and recreated. The function prototype for OSTmrCreate()
is shown below as a quick reference:
Once created, a timer can be started (or restarted) and stopped as often as is necessary. Timers can be created to operate in one of three modes: One-shot, Periodic (no initial delay), and Periodic (with initial delay).