#ifndef _PT_H_ #define _PT_H_ #include "stm32f10x.h" // typedef unsigned short lc_t; #define LC_INIT(s) s = 0; #define LC_RESUME(s) switch(s) { case 0: #define LC_SET(s) s = __LINE__; case __LINE__: #define LC_END(s) default: s= 0;} ///////////////////////////////////////////////////////////////////////////// struct pt { lc_t lc; }; //任务状态 enum PT_State{PT_WAITING=0,PT_YIELDED,PT_EXITED,PT_ENDED}; //任务初始化 #define PT_INIT(pt) LC_INIT((pt)->lc) //声明任务返回值 #define PT_THREAD(name_args) char name_args //任务开始 #define PT_BEGIN(pt) {char PT_YIELD_FLAG = PT_YIELDED; LC_RESUME((pt)->lc) //任务结束 #define PT_END(pt) LC_END((pt)->lc); PT_YIELD_FLAG = 0; \ PT_INIT(pt); return PT_ENDED; } //任务等待直到条件成立 #define PT_WAIT_UNTIL(pt, condition) \ do { \ LC_SET((pt)->lc); \ if(!(condition)) { \ return PT_WAITING; \ } \ } while(0) //任务在条件成立时循环 #define PT_WAIT_WHILE(pt, cond) PT_WAIT_UNTIL((pt), !(cond)) //等待子任务退出 #define PT_WAIT_THREAD(pt, thread) PT_WAIT_WHILE((pt), PT_SCHEDULE(thread)) //建立子任务直到子任务退出运行 #define PT_SPAWN(pt, child, thread) \ do { \ PT_INIT((child)); \ PT_WAIT_THREAD((pt), (thread)); \ } while(0) //重新启动任务 #define PT_RESTART(pt) \ do { \ PT_INIT(pt); \ return PT_WAITING; \ } while(0) //任务退出 #define PT_EXIT(pt) \ do { \ PT_INIT(pt); \ return PT_EXITED; \ } while(0) #define PT_SCHEDULE(f) ((f) < PT_EXITED) //休眠 #define PT_YIELD(pt) \ do { \ PT_YIELD_FLAG = PT_WAITING; \ LC_SET((pt)->lc); \ if(PT_YIELD_FLAG == PT_WAITING) { \ return PT_YIELDED; \ } \ } while(0) //信号量 struct pt_sem { unsigned int count; }; //初始化信号量 #define PT_SEM_INIT(s, c) (s)->count = c //等待信号量 #define PT_SEM_WAIT(pt, s) \ do { \ PT_WAIT_UNTIL(pt, (s)->count > 0); \ --(s)->count; \ } while(0) //设置信号量 #define PT_SEM_SIGNAL(pt, s) ++(s)->count struct timer {uint32_t start; int interval;}; extern uint32_t TickCount ; static uint32_t clock_time(void) { uint32_t tick; tick = TickCount; //1ms return tick; } static int timer_expired(struct timer *t) { return (clock_time() - t->start) >= t->interval; } static void timer_set(struct timer *t, int interval) { t->interval = interval; t->start = clock_time(); } #endif