#include <at89x52.h>
#define MAX_TASKS 2 // 最大任务数
#define MAX_TASK_DEP 12 // 每个任务的栈容量
unsigned char idata task_stack[MAX_TASKS][MAX_TASK_DEP]; // 任务栈
unsigned char idata task_sp[MAX_TASKS]; // 每个任务的运行位置
unsigned char task_id = 0; // 当前任务号
sbit LED = P1^4;
sbit LED2 = P1^5;
// 任务装入函数
void task_load(unsigned int fn, unsigned char tid)
{
task_sp[tid] = (unsigned char)&task_stack[tid][1];
task_stack[tid][0] = fn & 0xff;
task_stack[tid][1] = fn >> 8;
}
// 任务切换函数
void task_switch(void)
{
task_sp[task_id] = SP;
if (++task_id == MAX_TASKS)
task_id = 0;
SP = task_sp[task_id];
}
void delay(unsigned char n)
{
char i;
while (n--)
for (i = 0; i < 115; i++);
}
void task1(void)
{
while (1)
{
LED = 0;
delay(500);
LED = 1;
delay(500);
task_switch();
}
}
void task2(void)
{
while (1)
{
LED2 = 0;
delay(500);
LED2 = 1;
delay(500);
task_switch();
}
}
int main(void)
{
task_load(task1, 0);
task_load(task2, 1);
SP = task_sp[task_id];
return 0;
}