前后台系统设计中,常常会在多个模块需要定时器功能。而处理器的硬件定时器总是很有限的,这时候就需要使用软件定时器。基于链表的软件定时器,只需要使用一个硬件定时器模块,可以很方便的在各个模块定义自己的定时器,并插入链表中,在不需要的时候从链表中删除即可。
SortTimer.c文件:
#include "DSP28x_Project.h" // Device Headerfile and Examples Include File
#include "stdlib.h"
#include "SoftTimer.h"
SOFT_TIMER_LINK timer_link_head = {0,0,NULL};
//中断服务子程序
interrupt void cpu_timer1_isr(void)
{
SOFT_TIMER_LINK * p;
p = &timer_link_head;
while(p != NULL)
{
if(p->run == 1 && p->counter != 0)
{
p->counter--;
}
p = p->next;
};
EDIS;
}
//添加虚拟定时器
unsigned char soft_timer_add(SOFT_TIMER_LINK *timer)
{
SOFT_TIMER_LINK * p;
p = &timer_link_head;
while(p->next != NULL)
{
p = p->next;
};
p->next = timer;
timer->next = NULL;
return 1;
}
//删除虚拟定时器
unsigned char soft_timer_delete(SOFT_TIMER_LINK *timer)
{
SOFT_TIMER_LINK * p;
p = &timer_link_head;
if(p->next == NULL)
{
return 0;//空表
}
while(p->next!= NULL)
{
if(p->next == timer)
{
break;
}
else
{
p = p->next;
}
};
p->next = timer->next;
timer->run = 0;
timer->counter = 0;
return 1;
}
//启动虚拟定时器
void soft_timer_start(SOFT_TIMER_LINK *timer,unsigned int time_set)
{
timer->run = 1;
timer->counter = time_set;
}
//查询虚拟定时器是否超时
unsigned char soft_timer_expire(SOFT_TIMER_LINK *timer)
{
if(timer->run == 1 && timer->counter == 0)
{
timer->run = 0;
return 1;
}
else
{
return 0;
}
}
SoftTimer.h文件:
#ifndef SOFTTIMER_H
#define SOFTTIMER_H
typedef struct SOFT_TIMER
{
unsigned int counter;
unsigned char run;
struct SOFT_TIMER *next;
} SOFT_TIMER_LINK;
extern SOFT_TIMER_LINK timer_link_head;
unsigned char soft_timer_add(SOFT_TIMER_LINK *timer);
unsigned char soft_timer_delete(SOFT_TIMER_LINK *timer);
void soft_timer_start(SOFT_TIMER_LINK *timer,unsigned int time_set);
unsigned char soft_timer_expire(SOFT_TIMER_LINK *timer);
#endif
使用步骤说明:
// step1 配置定时器周期,将中断入口地址指向 SoftTimer.c文件中的定时器中断服务子函数
// step2 定义想要使用的定时器例如:
SOFT_TIMER_LINK timer_1;
// step3 将它添加到链表中
soft_timer_add(&timer_1);
// step4 将它添加到链表中启动定时器
soft_timer_start(&timer_1,1000);
// 等待定时器超时
if(soft_timer_expire(&timer_1))
{
//do sth;
//soft_timer_start(&timer_1,1000);
}