看看层次https://blog.csdn.net/weixin_42381351/article/details/100532537
这个很好学校
#ifndef tslTimer_h
#define tslTimer_h
#include <stdint.h>
#define MAX_TIMERS 5
typedef void (*TimerCallback)(void);
typedef struct {
uint8_t start;
uint32_t cnt;
uint32_t timeout;
TimerCallback callback;
}TslTimer_t;
typedef struct {
TslTimer_t commands[MAX_TIMERS];
uint16_t numCmds;
} TslTimerCmdList_t;
typedef struct {
TslTimer_t * (*creat)(uint32_t timerout ,uint8_t start, TimerCallback callback);
int8_t (*stop) (TslTimer_t *timer);
int8_t (*start)(TslTimer_t *timer);
}TslTimerOps_t;
void timerHandle(uint32_t tick);
/*
* 设置当前的滴答数,以ms为单位
* 备注:需要在定时器中断中调用或者开一个线程调用timerHandle
tslGatewaySetMsTimerCount(1);
void tslGatewaySetMsTimerCount(uint32_t tick) {
timerMsCount += tick;
timerHandle(tick);
}
*/
extern TslTimerOps_t timer;
/*
timer.creat(1, TRUE, sdkTimerHandle);
建立一个硬任务1MS执行一次函数sdkTimerHandle
*/
#endif
#include "tslTimer.h"
#include <stdio.h>
static TslTimerCmdList_t timerList;
void timerHandle(uint32_t tick) {
for (int i = 0; i < MAX_TIMERS; i++) {
TslTimer_t *timer = &timerList.commands[i];
if (timer->start == 1) {
timer->cnt += tick;
if (timer->cnt >= timer->timeout) {
timer->cnt = 0;
if (timer->callback != NULL) {
timer->callback();
}
}
}
}
}
TslTimer_t *findEmptyTimer(void) {
for (int i = 0; i < MAX_TIMERS; i++) {
if (timerList.commands[i].callback == NULL) {
return &timerList.commands[i];
}
}
return NULL;
}
TslTimer_t *timerCreat(uint32_t timerout , uint8_t start, TimerCallback callback) {
TslTimer_t *timer = findEmptyTimer();
timer->timeout = timerout;
timer->start = start;
timer->callback = callback;
return timer;
}
int8_t timerStart(TslTimer_t *timer) {
for (int i = 0; i < MAX_TIMERS; i++) {
TslTimer_t *time= &timerList.commands[i];
if (timer == time) {
time->start = 1;
time->cnt = 0;
}
}
return 0;
}
int8_t timerStop(TslTimer_t *timer) {
for (int i = 0; i < MAX_TIMERS; i++) {
TslTimer_t *time= &timerList.commands[i];
if (timer == time) {
time->start = 0;
time->cnt = 0;
}
}
return 0;
}
TslTimerOps_t tslTimer = {
.creat = timerCreat,
.stop = timerStop,
.start = timerStart,
};