有趣的时间任务,简单时分的多任务实现
作者:互联网
控制控制每个函数每秒执行次数。
方法1相对方法2更整洁,不用每次在时钟中断里添加新的计数值。减低代码间耦合,非常nice!
方法1:
void __attribute__((interrupt)) _SysTick_exception (void)
{
SYSTICK_Counter_Updata();
SysTick++;
}
//关键函数:计时判断。
uint32_t IsSysTimeout(uint32_t *timer)
{
if(*timer == 0)
return 1;
else if((SysTick - *timer) <= 0x7fffffff)
{
*timer = 0;
return 1;
}
else
return 0;
}
void SetSysTimer(uint32_t *timer,uint32_t TimeParaVal)
{
*timer = TimeParaVal + SysTick;
if(*timer == 0) *timer = 1; //not set timer to 0 for timer is running
}
//main主循环
int main()
{
uint32_t loop10hz,loop1000hz;
...
while(1)
{
if(IsSysTimeout(&loop10hz))
{
SetSysTimer(&loop10hz,100);
Demo_LED1_ON_OFF();
}
if(IsSysTimeout(&loop1000hz))
{
SetSysTimer(&loop1000hz,1);
Demo_LED2_ON_OFF();
}
}
}
方法2
void TIM4_IRQHandler(void) //1ms中断一次
{
if( TIM_GetITStatus(TIM4 , TIM_IT_Update) != RESET )
{
anyCnt++;
loop200HzCnt++;
loop100HzCnt++;
if(++loop50HzCnt * 50 >= (1000))
{
loop50HzCnt=0;
loop50HzFlag=1;
}
if(++loop20HzCnt * 20 >=1000 )
{
loop20HzCnt=0;
loop20HzFlag=1;
}
if(++loop10HzCnt * 10 >=1000 )
{
loop10HzCnt=0;
loop10HzFlag=1;
}
TIM_ClearITPendingBit(TIM4 , TIM_FLAG_Update); //清除中断标志
}
}
int main(void)
{
while (1)
{
if(anyCnt>=5)
{
anyCnt=0;
realExecPrd[0]=micros()-startTime[0];
startTime[0]=micros();
....
execTime[0]=micros()-startTime[0]; //测量任务执行时间,CPU占用率
}
//100Hz Loop
if(loop100HzCnt>=10)
{
loop100HzCnt=0;
realExecPrd[1]=micros()-startTime[1];
startTime[1]=micros();
....
execTime[1]=micros()-startTime[1];
}
//50Hz Loop
if(loop50HzFlag)
{
loop50HzFlag=0;
realExecPrd[3]=micros()-startTime[3];
startTime[3]=micros();
...
execTime[3]=micros()-startTime[3];
...
}
//10Hz loop
if(loop10HzFlag)
{
loop10HzFlag=0;
realExecPrd[2]=micros()-startTime[2];
startTime[2]=micros();
....
execTime[2]=micros()-startTime[2];
}
}
标签:时分,++,micros,void,timer,uint32,startTime,有趣,多任务 来源: https://blog.csdn.net/qq_27741499/article/details/121157668