Car/Service/Src/timer.c
2024-07-21 08:19:42 +08:00

65 lines
1.3 KiB
C

#include "timer.h"
#include "tim.h"
#include <math.h>
typedef struct Event
{
void (*func)(void);
uint16_t time;
uint8_t enabled;
} Event;
static Event event[EVENT_MAX];
static uint32_t time_cnt;
static uint32_t time_lcm = 1;
uint32_t gcd(uint32_t a, uint32_t b);
uint32_t lcm(uint32_t a, uint32_t b);
void TIMER_Count(void);
void TIMER_Init(void)
{
HAL_TIM_RegisterCallback(&htim4, HAL_TIM_PERIOD_ELAPSED_CB_ID, TIMER_Count);
HAL_TIM_Base_Start_IT(&htim4);
}
/// @brief 注册定时回调事件
/// @param func 回调函数 void func(void)
/// @param loop_time 定时时间,单位毫秒
void TIMER_AddLoopEvent(uint8_t type, void (*func)(void), uint16_t loop_time)
{
event[type].func = func;
event[type].time = loop_time;
event[type].enabled = 1;
time_lcm = lcm(time_lcm, loop_time);
}
void TIMER_DelLoopEvent(uint8_t type)
{
event[type].enabled = 0;
time_lcm /= event[type].time;
}
void TIMER_Count(void)
{
++time_cnt;
for (uint8_t i = 0; i < EVENT_MAX; ++i)
if (event[i].enabled && time_cnt % event[i].time == 0)
event[i].func();
if (time_cnt == time_lcm)
time_cnt = 0;
}
uint32_t gcd(uint32_t a, uint32_t b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
uint32_t lcm(uint32_t a, uint32_t b)
{
return a / gcd(a, b) * b;
}