标签:
1 main.c 2 3 #include "reg51.h" 4 #include "os_cfg.h" 5 #define TASK_DELAY0 TIME_PER_SEC/1 //任务执行频度为1Hz 6 #define TASK_DELAY1 TIME_PER_SEC/2 //任务执行频度为2Hz 7 #define TASK_DELAY2 TIME_PER_SEC/10 //任务执行频度为10Hz 8 #define TASK_DELAY3 TIME_PER_SEC/20 //任务执行频度为20Hz 9 10 void (* code task[])() = {task0,task1,task2,task3}; 11 12 sbit LED0 = P1^0; 13 sbit LED1 = P1^1; 14 sbit LED2 = P1^2; 15 sbit LED3 = P1^3; 16 17 /*main主函数*/ 18 void main(void) 19 { 20 unsigned char i; 21 os_timer0_init(); 22 EA = 1; //开总中断 23 24 while(1) 25 { 26 for(i=0;i<MAX_TASK;i++) 27 if (task_delay[i]==0) {run(task[i]); break;} //任务优先级调度 28 } 29 } 30 31 32 void task0(void) 33 { 34 LED0 = !LED0; 35 task_delay[0] = TASK_DELAY0; 36 } 37 38 void task1(void) 39 { 40 LED1 = !LED1; 41 task_delay[1] = TASK_DELAY1; 42 } 43 44 void task2(void) 45 { 46 LED2 = !LED2; 47 task_delay[2] = TASK_DELAY2; 48 } 49 50 void task3(void) 51 { 52 static unsigned char state=0; 53 switch (state) 54 { 55 case 0: 56 LED3 = !LED3; 57 state = 1; 58 task_delay[3] = TASK_DELAY3; 59 break; 60 61 case 1: 62 LED3 = !LED3; 63 state = 2; 64 task_delay[3] = TASK_DELAY3*2; 65 break; 66 67 case 2: 68 LED3 = !LED3; 69 state = 0; 70 task_delay[3] = TASK_DELAY3*4; 71 break; 72 73 default: 74 break; 75 } 76 } 77 78 79 80 os_cfg.h 81 82 #include "reg51.h" 83 #define TIME_PER_SEC 200 //定义任务时钟频率,200Hz 84 #define CLOCK 22118400 //定义时钟晶振,单位Hz 85 #define MAX_TASK 4 //定义任务数量 86 extern void task0(void); 87 extern void task1(void); 88 extern void task2(void); 89 extern void task3(void); 90 extern unsigned char task_delay[MAX_TASK]; 91 extern void run(void (*ptask)()); 92 extern void os_timer0_init(void); 93 94 95 96 os_cfg.c 97 98 #include "os_cfg.h" 99 unsigned char task_delay[MAX_TASK]; 100 101 //定时器0初始化 102 void os_timer0_init(void) 103 { 104 unsigned char i; 105 for(i=0;i<MAX_TASK;i++) task_delay[i]=0; //赋初值task_delay[0]=0,task_delay[1]=0,task_delay[2]=0,task_delay[3]=0 106 TMOD = (TMOD & 0XF0) | 0X01; //定时器0工作在模式1,16Bit定时器模式 107 TH0 = (65536-CLOCK/TIME_PER_SEC/12) / 256; //CRY_OSC,TIME_PER_SEC在easycfg.h中配置 108 TL0 = (65536-CLOCK/TIME_PER_SEC/12) % 256; 109 TR0 =1; 110 ET0 =1; //开启定时器和中断 111 } 112 113 // 系统OS定时中断服务 114 void os_timer0(void) interrupt 1 115 { 116 unsigned char i; 117 TH0 = (65536-CLOCK/TIME_PER_SEC/12) / 256; //CRY_OSC,TIME_PER_SEC在easycfg.h中配置 118 TL0 = (65536-CLOCK/TIME_PER_SEC/12) % 256; 119 for(i=0;i<MAX_TASK;i++) if(task_delay[i]) task_delay[i]--; //每节拍对任务延时变量减1 ,减至 0 后,任务就绪。 120 } 121 122 void run(void (*ptask)()) 123 { 124 (*ptask)(); 125 }
标签:
原文地址:http://www.cnblogs.com/Andren/p/4556157.html