The Timer module provides a mechanism to execute a piece of code after a specified timeout period. This can be done through hardware timers. But hardware timers are limited and scarce resource in micro-controllers. The Timer module provides theoretically infinite number of software timers using only one hardware timer.
The Timer functions are declared in timer.h
. An opaque structure
timer_t
to store the timer’s internal state. The following example
blinks LED1 with a period of 2 seconds, and turns on LED2 after a
period of 10 seconds.
Listing 5.1. Timer Demonstration
#include <stdlib.h>
#include <board.h>
#include <timer.h>
timer_t timer1;
timer_t timer2;
void blink1(timer_t *timer) __reentrant
{
static bool state;
gpio_set_pin(LED1_GPIO, state);
state = !state;
/* For periodic timer, reschedule to a later time. */
timer_setup(timer, 2000);
}
void blink2(timer_t *timer) __reentrant
{
gpio_set_pin(LED2_GPIO, 0);
/* For one shot timer, unregister callback. */
timer_setcb(timer, NULL);
}
int main()
{
board_init();
timer_init();
gpio_init();
gpio_enable_pin(LED1_GPIO);
gpio_direction_output(LED1_GPIO, OFF);
timer_setup(&timer1, 2000); /* Periodic, 2s period */
timer_setcb(&timer1, blink1);
timer_setup(&timer2, 10000); /* One shot, after 10s */
timer_setcb(&timer2, blink2);
event_poll();
return 0;
}