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:(比較常規的用法)spa

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

使用2:code

u16 dely_500mS = setDelay(500);

while(1)

{
  ...

  if(checkDelay(dely_500mS )){}//表示計時時間到達了  ...
}
相關文章
相關標籤/搜索