26.单片机中利用定时器中断,在主流程while(1){}中设置每隔精确时间计量

void Timer0_ISR( ) interrupt 5
{
    CountMilliseconds++;//只负责自加,加到最大又重新从0开始
}
u16 setDelay(u16 t)
{
    return(CountMilliseconds + t - 1);                                             
}

u8 checkDelay (u16 t)//返回非零表示计时结束
{
    return(((t - CountMilliseconds) & 0x8000) >> 8);//当(t - CountMilliseconds)为正则&之后为0,当变为负数后因为是无符号整数,产生无穷大,那么非零
}

使用1:(比较常规的用法)

void delay_ms(u16 w)//延时多少mS
{
     u16 temp;
     temp = setDelay(w);
     while (!checkDelay(temp));
}

使用2:

u16 dely_500mS = setDelay(500);

while(1)

{
  ...

  if(checkDelay(dely_500mS )){}//表示计时时间到达了

  ...
}

 

posted @ 2015-07-30 17:27  fx427103  阅读(562)  评论(0编辑  收藏  举报