本帖最后由 CC2530 于 2011-5-28 08:00 编辑
四个任务,围成一圈,每两个任务之间一个信号量(共四个信号量),
四个任务一起竞争,同时获得左右两个信号量,LED亮。
#include "proj_incs.h"
extern "C" int __low_level_init(void);
__root int __low_level_init(void)
{
__disable_interrupt(); //任务切换前关闭中断
return 1;
}
#define LONG_DELAY_TICKS OS_TICKS_PER_SEC/10 //长延时100ms
#define SHORT_DELAY_TICKS OS_TICKS_PER_SEC/100 //短延时10ms
TSem Sem_1={.Count=1}; //信号量1
TSem Sem_2={.Count=1}; //信号量2
TSem Sem_3={.Count=1}; //信号量3
TSem Sem_4={.Count=1}; //信号量4
TSK_Implement(0) //任务0
{
__enable_interrupt();
while(1)
{
SEM_Pend(&Sem_4);
if(!SEM_Accept(&Sem_1))
{
SEM_Post(&Sem_4);
TSK_Delay(SHORT_DELAY_TICKS);
continue;
}
LED_1.On();
TSK_Delay(LONG_DELAY_TICKS);
LED_1.Off();
SEM_Post(&Sem_1);
SEM_Post(&Sem_4);
//TSK_Delay(LONG_DELAY_TICKS);
}
}
TSK_Implement(1) //任务1
{
__enable_interrupt(); //任务开始开中断
while(1)
{
SEM_Pend(&Sem_1);
if(!SEM_Accept(&Sem_2))
{
SEM_Post(&Sem_1);
TSK_Delay(SHORT_DELAY_TICKS);
continue;
}
LED_2.On();
TSK_Delay(LONG_DELAY_TICKS);
LED_2.Off();
SEM_Post(&Sem_2);
SEM_Post(&Sem_1);
//TSK_Delay(LONG_DELAY_TICKS);
}
}
TSK_Implement(2) //任务2
{
__enable_interrupt(); //任务开始开中断
while(1)
{
SEM_Pend(&Sem_2);
if(!SEM_Accept(&Sem_3))
{
SEM_Post(&Sem_2);
TSK_Delay(SHORT_DELAY_TICKS);
continue;
}
LED_3.On();
TSK_Delay(LONG_DELAY_TICKS);
LED_3.Off();
SEM_Post(&Sem_3);
SEM_Post(&Sem_2);
//TSK_Delay(LONG_DELAY_TICKS);
}
}
TSK_Implement(3) //任务3
{
__enable_interrupt(); //任务开始开中断
while(1)
{
SEM_Pend(&Sem_3);
if(!SEM_Accept(&Sem_4))
{
SEM_Post(&Sem_3);
TSK_Delay(SHORT_DELAY_TICKS);
continue;
}
LED_4.On();
TSK_Delay(LONG_DELAY_TICKS);
LED_4.Off();
SEM_Post(&Sem_4);
SEM_Post(&Sem_3);
//TSK_Delay(LONG_DELAY_TICKS);
}
}
int main()
{
__disable_interrupt(); //任务开始调度前,要关中断
// while(1);
LED_1.MakeOutput(); //LED_1设置为输出
LED_2.MakeOutput(); //LED_2设置为输出
LED_3.MakeOutput(); //LED_3设置为输出
LED_4.MakeOutput(); //LED_4设置为输出
HS_HeapInit(); //初始化堆
SysTick_Config(SystemCoreClock/1000 ); //系统节拍初始化
TSK_Init(0,0,200); //任务0,优先级0,堆栈200
TSK_Init(1,0,200); //任务1,优先级0,堆栈200
TSK_Init(2,0,200); //任务2,优先级0,堆栈200
TSK_Init(3,0,200); //任务3,优先级0,堆栈200
TSK_Start(); //任务开始调度(开始调度由空闲任务主函数切换到用户任务)
__enable_interrupt(); //空闲任务主函数开中断,空闲任务主函数也有自己单独的总中断标志位
while(1) //任务空闲时,运行这里
{
//SleepIdle(); //空闲休眠
}
} |