2024-07-18 11:29:28 +08:00
|
|
|
#include "timer.h"
|
2024-07-20 10:44:59 +08:00
|
|
|
#include "tim.h"
|
2024-07-21 08:19:42 +08:00
|
|
|
#include <math.h>
|
2024-07-20 10:44:59 +08:00
|
|
|
|
2024-07-18 11:29:28 +08:00
|
|
|
typedef struct Event
|
|
|
|
{
|
|
|
|
void (*func)(void);
|
|
|
|
uint16_t time;
|
|
|
|
uint8_t enabled;
|
|
|
|
} Event;
|
|
|
|
|
|
|
|
static Event event[EVENT_MAX];
|
2024-07-21 08:19:42 +08:00
|
|
|
static uint32_t time_cnt;
|
|
|
|
static uint32_t time_lcm = 1;
|
2024-07-18 11:29:28 +08:00
|
|
|
|
2024-07-21 08:19:42 +08:00
|
|
|
uint32_t gcd(uint32_t a, uint32_t b);
|
|
|
|
uint32_t lcm(uint32_t a, uint32_t b);
|
|
|
|
|
|
|
|
void TIMER_Count(void);
|
2024-07-18 11:29:28 +08:00
|
|
|
|
|
|
|
void TIMER_Init(void)
|
|
|
|
{
|
|
|
|
HAL_TIM_RegisterCallback(&htim4, HAL_TIM_PERIOD_ELAPSED_CB_ID, TIMER_Count);
|
|
|
|
HAL_TIM_Base_Start_IT(&htim4);
|
|
|
|
}
|
|
|
|
|
2024-07-21 08:19:42 +08:00
|
|
|
/// @brief 注册定时回调事件
|
2024-07-18 11:29:28 +08:00
|
|
|
/// @param func 回调函数 void func(void)
|
|
|
|
/// @param loop_time 定时时间,单位毫秒
|
2024-07-21 08:19:42 +08:00
|
|
|
void TIMER_AddLoopEvent(uint8_t type, void (*func)(void), uint16_t loop_time)
|
2024-07-18 11:29:28 +08:00
|
|
|
{
|
2024-07-21 08:19:42 +08:00
|
|
|
event[type].func = func;
|
|
|
|
event[type].time = loop_time;
|
|
|
|
event[type].enabled = 1;
|
|
|
|
time_lcm = lcm(time_lcm, loop_time);
|
2024-07-18 11:29:28 +08:00
|
|
|
}
|
|
|
|
|
2024-07-21 08:19:42 +08:00
|
|
|
void TIMER_DelLoopEvent(uint8_t type)
|
2024-07-18 11:29:28 +08:00
|
|
|
{
|
2024-07-21 08:19:42 +08:00
|
|
|
event[type].enabled = 0;
|
|
|
|
time_lcm /= event[type].time;
|
2024-07-18 11:29:28 +08:00
|
|
|
}
|
|
|
|
|
2024-07-21 08:19:42 +08:00
|
|
|
void TIMER_Count(void)
|
2024-07-18 11:29:28 +08:00
|
|
|
{
|
2024-07-21 08:19:42 +08:00
|
|
|
++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;
|
2024-07-18 11:29:28 +08:00
|
|
|
}
|
|
|
|
|
2024-07-21 08:19:42 +08:00
|
|
|
uint32_t gcd(uint32_t a, uint32_t b)
|
2024-07-18 11:29:28 +08:00
|
|
|
{
|
2024-07-21 08:19:42 +08:00
|
|
|
if (b == 0)
|
|
|
|
return a;
|
|
|
|
return gcd(b, a % b);
|
2024-07-18 11:29:28 +08:00
|
|
|
}
|
|
|
|
|
2024-07-21 08:19:42 +08:00
|
|
|
uint32_t lcm(uint32_t a, uint32_t b)
|
2024-07-18 11:29:28 +08:00
|
|
|
{
|
2024-07-21 08:19:42 +08:00
|
|
|
return a / gcd(a, b) * b;
|
2024-07-18 11:29:28 +08:00
|
|
|
}
|