金牌会员
- 积分
- 1236
- 金钱
- 1236
- 注册时间
- 2015-5-14
- 在线时间
- 352 小时
|
下面是一个自己写的简易的软件定时器,欢迎大家拍砖,一起来谈论。
#ifndef __SOFTWARE_TIMER__
#define __SOFTWARE_TIMER__
//头文件
#include <p18cxxx.h>
#include <string.h>
#include "../heard/include.h"
//最大定时器个数
#define SOFTWARE_TIMER_MAX_TASKS 3
//软件定时器数组
typedef struct _SoftwareTimer_struct{
//用户层
void (*callback)(void); //回调函数指针
_UWORD delay_time; //延时时间,多少个心跳周期
//内部实现层
BOOL RunFlag; //任务运行标志
}SoftwareTimer_struct;
//软件定时器初始化函数
void SoftwareTimerInit(void);
//放到心跳定时中断函数中
void SoftwareTimerUpdate(void);
//放到main主循环中
void SoftwareTimerUserScheduling(void);
//用户函数
BOOL SoftwareTimerUserAddTask(void (*callback)(),const _UWORD DELAY);
BOOL SoftwareTimerUserDelTask(void (*callback)());
BOOL SoftwareTimerUserHangTask(void (*callback)());
BOOL SoftwareTimerUserContiueTask(void (*callback)());
#endif
#include "../heard/software_timer.h"
static SoftwareTimer_struct SoftwareTimerData[SOFTWARE_TIMER_MAX_TASKS];
#define SoftwareTimerDataLong sizeof(SoftwareTimerData)
//软件定时器初始化函数
void SoftwareTimerUserInit(void)
{
memset(SoftwareTimerData,0,SoftwareTimerDataLong);
}
//软件定时器更新函数
void SoftwareTimerUpdate(void)
{
_UBYTE Index;
for(Index=0;Index<SOFTWARE_TIMER_MAX_TASKS;Index++)
{
if((SoftwareTimerData[Index].RunFlag) && (SoftwareTimerData[Index].delay_time))
{
SoftwareTimerData[Index].delay_time--;
}
}
}
//软件定时器执行函数
void SoftwareTimerUserScheduling(void)
{
_UBYTE Index;
for(Index=0;Index<SOFTWARE_TIMER_MAX_TASKS;Index++)
{
if((SoftwareTimerData[Index].RunFlag) && (!SoftwareTimerData[Index].delay_time))
{
if(SoftwareTimerData[Index].callback)
SoftwareTimerData[Index].callback();
SoftwareTimerData[Index].RunFlag=0;
SoftwareTimerData[Index].callback=0;
}
}
}
//软件定时器添加函数
BOOL SoftwareTimerUserAddTask(void (*callback)(),const _UWORD DELAY)
{
_UBYTE Index;
for(Index=0;Index<SOFTWARE_TIMER_MAX_TASKS;Index++)
{
if(!SoftwareTimerData[Index].callback)
{
SoftwareTimerData[Index].callback =callback;
SoftwareTimerData[Index].delay_time =DELAY;
SoftwareTimerData[Index].RunFlag =1;
return TRUE;
}
}
return FALSE;
}
//软件定时器删除函数
BOOL SoftwareTimerUserDelTask(void (*callback)())
{
_UBYTE Index;
for(Index=0;Index<SOFTWARE_TIMER_MAX_TASKS;Index++)
{
if(SoftwareTimerData[Index].callback==callback)
{
SoftwareTimerData[Index].RunFlag =0;
SoftwareTimerData[Index].callback =0;
SoftwareTimerData[Index].delay_time =0;
return TRUE;
}
}
return FALSE;
}
//软件定期挂起函数
BOOL SoftwareTimerUserHangTask(void (*callback)())
{
_UBYTE Index;
for(Index=0;Index<SOFTWARE_TIMER_MAX_TASKS;Index++)
{
if(SoftwareTimerData[Index].callback==callback)
{
SoftwareTimerData[Index].RunFlag =0;
return TRUE;
}
}
return FALSE;
}
//软件定期继续运行函数
BOOL SoftwareTimerUserContiueTask(void (*callback)())
{
_UBYTE Index;
for(Index=0;Index<SOFTWARE_TIMER_MAX_TASKS;Index++)
{
if(SoftwareTimerData[Index].callback==callback)
{
SoftwareTimerData[Index].RunFlag =1;
return TRUE;
}
}
return FALSE;
}
|
|