说明:软件定时器不是定时器,是应用于操作系统中的一种定时回调功能函数的算法。 算法结构:本软件定时器,包含一个链表,一个定时器任务。 void updateSystemTime(void)函数要在定时器溢出中断中被调用。
- timer_callback.h头文件
#ifndef _TIMER_CALLBACK_H_#define _TIMER_CALLBACK_H_#include "board.h"#define LIST_OK 0#define ERR_LIST_EMPTY 1#define ONLY_ONE 0extern u32 system_time;#define GET_TICK(tick) \ do { \ tick = system_time; \ } while (tick != system_time) //#define NULL 0typedef struct{ u32 tick_temp; u32 tick_begin;}TICK; typedef void (*timer_callback_function)(void*);typedef struct callback_timer_type{ unsigned char timer_index; unsigned char mode; unsigned long long time; unsigned long long start_time; timer_callback_function func;}callback_timer;typedef callback_timer DataType;typedef struct node_l{ DataType data_t; struct node_l *next_node;}nodelist;void node_test(void );void createNodeList(void);void addNode(nodelist* L);u8 rmNode(nodelist* L);int getNodeNum(void);void timer_task(void);void callback_TimerInit(void );u32 getSystemTime(void);void updateSystemTime(void);#endif
- timer_callback.c源文件
#include "timer_callback.h"#include "stdlib.h"//#include "string.h"#include "stdio.h"#include "board.h"/*定义一个链表头指针*/nodelist *nl;/*系统时间,单位ms*/u32 system_time=0;void createNodeList(){ nl = NULL;}void addNode(nodelist* L){ nodelist* tp; tp = nl; if(nl==NULL) { nl=(nodelist*)malloc(sizeof(nodelist)); *nl=*L; nl->next_node=NULL; return; } while(tp->next_node!=NULL) { tp=tp->next_node; } tp->next_node=(nodelist*)malloc(sizeof(nodelist)); *(tp->next_node)=*L; tp->next_node->next_node=NULL;}u8 rmNode(nodelist* L){ nodelist *tp,*tp_head; tp = nl; while(tp!=NULL) { if(tp==nl) { /*根据索引号删除*/ if(nl->data_t.timer_index==L->data_t.timer_index) { nl=nl->next_node; free(tp); tp=nl; } else { tp_head=nl; } } else { /*根据索引号删除*/ if(tp->data_t.timer_index==L->data_t.timer_index) { tp_head->next_node=tp->next_node; free(tp); tp=tp_head->next_node; } else { tp_head=tp; tp=tp->next_node; } } } return LIST_OK;}int getNodeNum(){ int num=0; nodelist* tp; tp=nl; while(tp!=NULL) { num++; tp=tp->next_node; } return num;}void timer_task(){ nodelist* tp; nodelist* rm_temp; tp=nl; if(nl!=NULL) { if((nl->data_t.time)<(system_time-nl->data_t.start_time)) { (nl->data_t.func)(NULL); if(nl->data_t.mode==ONLY_ONE) { /*记录要删除节点*/ rm_temp=nl; nl=nl->next_node; /*删除节点*/ free(rm_temp); } else { nl->data_t.start_time=system_time; } } } else { return; } while(tp->next_node!=NULL) { if((tp->next_node->data_t.time)<(system_time-tp->next_node->data_t.start_time)) { (tp->next_node->data_t.func)(NULL); if(tp->next_node->data_t.mode==ONLY_ONE) { /*记录要删除节点*/ rm_temp=tp->next_node; tp->next_node=tp->next_node->next_node; /*删除节点*/ free(rm_temp); if(tp->next_node==NULL) { return; } } else { tp->next_node->data_t.start_time=system_time; } } tp=tp->next_node; }}void callback_TimerInit(){ //timer4Init();}u32 getSystemTime(void){ return system_time;}void updateSystemTime(void){ system_time++;}