这是我的一个非常相似的应用程序的一些代码,适用于小型 MCU 应用程序,并且符合 MISRA-C。它基于调用应用程序中静态分配的“软件计时器”。项目中的多个模块可以使用相同的计时器模块,因为它在内部使用链表来跟踪所有计时器。
从 1ms 中断中调用 tim_traverse_timers()。如果你有非常高的精度要求,你可能需要在调用函数之前清除中断源,这样函数本身的“代码抖动”开销就不会影响定时器。
如果您需要更长的延迟,然后是 65535 毫秒,只需将计数器和间隔更改为 uint32。
typedef struct timer
{
struct timer* next; /* Next timer in the linked list */
uint16 counter; /* 16-bit timer counter */
uint16 interval; /* The interval between triggers */
BOOL is_enabled; /* Timer enabled/disabled */
void (*callback_func)(void); /* Callback timer function */
} Timer;
static Timer* timer_list;
void tim_init (void)
{
timer_list = NULL;
}
void tim_add (Timer* timer,
void (* callback_func)(void),
uint16 interval_ms,
BOOL enabled)
{
tim_enable_interrupt (FALSE); /* hardware function disabling timer interrupt */
timer->callback_func = callback_func;
timer->counter = 0U;
timer->interval = interval_ms;
timer->is_enabled = enabled;
timer->next = timer_list;
timer_list = timer;
tim_enable_interrupt (TRUE);
}
void tim_enable (Timer* timer, BOOL enable)
{
if(enable)
{
timer->counter = 0U; /* Reset counter each time function is called */
}
timer->is_enabled = enable;
}
void tim_traverse_timers (void)
{
Timer* timer;
for(timer=timer_list; timer!=NULL; timer=timer->next)
{
if(timer->is_enabled == TRUE)
{
timer->counter++;
if(timer->counter == timer->interval)
{
timer->counter = 0U;
timer->callback_func();
}
}
}
}
#include "timer.h"
void my_func (void); /* lights some LED etc... */
void my_other_func (void);
void main (void)
{
Timer some_task;
Timer some_other_task;
...
tim_init();
...
tim_add(&some_task, &my_func, SOME_DELAY_IN_MS, TRUE);
tim_add(&some_other_task, &my_other_func, SOME_OTHER_DELAY_IN_MS, TRUE);
...
}