main.c #include "reg51.h"
#include "os_cfg.h"
#define TASK_DELAY0 TIME_PER_SEC/1 //任务执行频度为1Hz
#define TASK_DELAY1 TIME_PER_SEC/2 //任务执行频度为2Hz
#define TASK_DELAY2 TIME_PER_SEC/10 //任务执行频度为10Hz
#define TASK_DELAY3 TIME_PER_SEC/20 //任务执行频度为20Hz void (* code task[])() = {task0,task1,task2,task3}; sbit LED0 = P1^;
sbit LED1 = P1^;
sbit LED2 = P1^;
sbit LED3 = P1^; /*main主函数*/
void main(void)
{
unsigned char i;
os_timer0_init();
EA = ; //开总中断 while()
{
for(i=;i<MAX_TASK;i++)
if (task_delay[i]==) {run(task[i]); break;} //任务优先级调度
}
} void task0(void)
{
LED0 = !LED0;
task_delay[] = TASK_DELAY0;
} void task1(void)
{
LED1 = !LED1;
task_delay[] = TASK_DELAY1;
} void task2(void)
{
LED2 = !LED2;
task_delay[] = TASK_DELAY2;
} void task3(void)
{
static unsigned char state=;
switch (state)
{
case :
LED3 = !LED3;
state = ;
task_delay[] = TASK_DELAY3;
break; case :
LED3 = !LED3;
state = ;
task_delay[] = TASK_DELAY3*;
break; case :
LED3 = !LED3;
state = ;
task_delay[] = TASK_DELAY3*;
break; default:
break;
}
} os_cfg.h #include "reg51.h"
#define TIME_PER_SEC 200 //定义任务时钟频率,200Hz
#define CLOCK 22118400 //定义时钟晶振,单位Hz
#define MAX_TASK 4 //定义任务数量
extern void task0(void);
extern void task1(void);
extern void task2(void);
extern void task3(void);
extern unsigned char task_delay[MAX_TASK];
extern void run(void (*ptask)());
extern void os_timer0_init(void); os_cfg.c #include "os_cfg.h"
unsigned char task_delay[MAX_TASK]; //定时器0初始化
void os_timer0_init(void)
{
unsigned char i;
for(i=;i<MAX_TASK;i++) task_delay[i]=; //赋初值task_delay[0]=0,task_delay[1]=0,task_delay[2]=0,task_delay[3]=0
TMOD = (TMOD & 0XF0) | 0X01; //定时器0工作在模式1,16Bit定时器模式
TH0 = (-CLOCK/TIME_PER_SEC/) / ; //CRY_OSC,TIME_PER_SEC在easycfg.h中配置
TL0 = (-CLOCK/TIME_PER_SEC/) % ;
TR0 =;
ET0 =; //开启定时器和中断
} // 系统OS定时中断服务
void os_timer0(void) interrupt
{
unsigned char i;
TH0 = (-CLOCK/TIME_PER_SEC/) / ; //CRY_OSC,TIME_PER_SEC在easycfg.h中配置
TL0 = (-CLOCK/TIME_PER_SEC/) % ;
for(i=;i<MAX_TASK;i++) if(task_delay[i]) task_delay[i]--; //每节拍对任务延时变量减1 ,减至 0 后,任务就绪。
} void run(void (*ptask)())
{
(*ptask)();
}