本帖最后由 zjsxwc 于 2013-3-21 16:53 编辑
今天在看了rainyss大神的帖子后,在我的52上写了个调度器。
- #include <reg52.h>
- #define MAX_TASKS 3
- #define MAX_TASK_DEP 24
- unsigned char idata task_stack[MAX_TASKS][MAX_TASK_DEP]={0};
- unsigned char idata * task_sp[MAX_TASKS];
- unsigned char idata task_old[MAX_TASKS]={0};
- unsigned char task_id;
- unsigned char idata task_die[MAX_TASKS]={0};
- unsigned char task_time_slice[MAX_TASKS][2]={
- {0xC0,0xFF},//ʱ¼äƬ
- {0xC2,0xFF},
- {0xC1,0xFF},
- };
- void Task_clear_REG(){
- ACC=0;
- B=0;
- PSW=0;
- }
- void Start_Timer2(){
- EXEN2=0;
- C_T2=0;
- RCLK=0;
- TCLK=0;
- CP_RL2=0;
-
- RCAP2L=task_time_slice[0][0];
- RCAP2H=task_time_slice[0][1];
- TL2=task_time_slice[0][0];
- TH2=task_time_slice[0][1];
-
- PT2=1;
- TR2=1;
- ET2=1;
- EA=1;
- }
- void Init_OS(){
- Start_Timer2();
- }
- void Kill_task(unsigned char tid){
- task_die[tid]=1;
- }
- void Revive_task(unsigned char tid){
- task_die[tid]=0;
- }
- void task_load(unsigned int fn, unsigned char tid){
- task_sp[tid] = task_stack[tid] + 1;
- task_stack[tid][0] = (unsigned int)fn & 0xff;
- task_stack[tid][1] = (unsigned int)fn >> 8;
- }
- #define os_start(tid) {task_id = tid,SP = task_sp[tid];return;}
- void task1()
- {
- static unsigned char i;
-
- while(1){
- i++;
- }
- }
- void task2()
- {
- static unsigned char j;
-
- while(1){
- j+=1;
- j+=2;
- j+=3;
- j+=4;
- j+=5;
- j+=6;
- j+=7;
- j*=8;
- j+=9;
- j+=10;
- j+=55;
- j+=767;
- j+=2;
- j+=2;
- j+=44;
- j*=3;
- j+=1;
- j+=66;
- j*=43;
- j+=7;
- j+=98;
- j*=7;
- j+=332;
- j+=44;
- j+=33;
- j+=324;
- Kill_task(1);//finish task2,and suicide
- }
- }
- void task3(){
- static unsigned char k;
-
- while(1){
- k+=3;
- }
- }
- void main(){
- task_load(task1, 0);
- task_load(task2, 1);
- task_load(task3, 2);
- Init_OS();
- os_start(0);
- }
- void task_switch() interrupt 5
- {
- unsigned char R[5]={0};//let keil C51 know that R0--R7/B/acc/psw/dptr must be pushpop in the stack!
- TR2=0;
- task_old[task_id]=1;
- task_sp[task_id]=SP;
-
-
- while(1){
- if(++task_id == MAX_TASKS)
- task_id = 0;
- if (task_die[task_id]!=1) break;
- }
-
- if (task_old[task_id])
- SP=task_sp[task_id];
- else{
- *(task_sp[task_id]+1)=0;//acc
- *(task_sp[task_id]+2)=0;//B
- *(task_sp[task_id]+3)=0;//dpoh
- *(task_sp[task_id]+4)=0;//dpol
- *(task_sp[task_id]+5)=0;//psw
- *(task_sp[task_id]+6)=0;//r0
- *(task_sp[task_id]+7)=0;//r1
- *(task_sp[task_id]+8)=0;//r2
- *(task_sp[task_id]+9)=0;//r3
- *(task_sp[task_id]+10)=0;//r4
- *(task_sp[task_id]+11)=0;//r5
- *(task_sp[task_id]+12)=0;//r6
- *(task_sp[task_id]+13)=0;//r7
-
- task_sp[task_id]=task_sp[task_id]+13;
- SP = task_sp[task_id];
- }
-
- TF2=0;
- TL2=task_time_slice[task_id][0];
- TH2=task_time_slice[task_id][1];
- TR2=1;
- return;
- }
复制代码已改,由于使用中断服务函数时C51会自动保持ACCPSWBR0--R7dptr到相应任务堆栈所以省下了开辟空间保证这些寄存器的事情.
一周热门 更多>