定時(shí)器中斷的計(jì)時(shí)問題 前些天看到一個(gè)定時(shí)器中斷的計(jì)時(shí)問題,那里面采用的答案似乎是,中斷執(zhí)行以后才開始再次計(jì)時(shí),對此不敢茍同,考慮以下程序,0.1秒表計(jì)時(shí)
#include<reg52.h>
unsignedchar code DuanMa[10]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};//
unsignedchar code WeiMa[]={0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f};
unsignedchar miao=0;
voidDelayUs2x(unsigned char t)//大致延時(shí)(2*t+5)us
{
while(--t);
}
voidDelayMs(unsigned int t)//大致延時(shí)1mS
{
while(t--)
{
DelayUs2x(245);
DelayUs2x(245);
}
}
/*------------------------------------------------
顯示函數(shù),用于動(dòng)態(tài)掃描數(shù)碼管
------------------------------------------------*/
voidDisplay(unsigned char dat)
{
P1=0xff;
P0=DuanMa[dat%10];
P1=0x7f;
DelayMs(3);
P1=0xff;
P0=DuanMa[(dat/10)%10]|0x80;
P1=0xbf;
DelayMs(3);
P1=0xff;
P0=DuanMa[(dat/100)%10];
P1=0xdf;
DelayMs(3);
}
/*------------------------------------------------
主函數(shù)
------------------------------------------------*/
voidmain (void)
{
TMOD |= 0x01;
TH0=(65536-2000)/256;
TL0=(65536-2000)%256; //2ms定時(shí)
EA=1;
ET0=1;
TR0=1;
while (1)
{
Display(miao);
}
}
/*------------------------------------------------
定時(shí)器中斷子程序
------------------------------------------------*/
voidTimer0_isr(void) interrupt 1
{
static unsigned char count=0;
TH0=(65536-2000)/256; //重新賦值 2ms
TL0=(65536-2000)%256;
count++;
if(count==50)
{
miao++;
count=0;
}
// DelayMs(1);
}
1:定時(shí)器是2MS定時(shí),中斷里面的 延時(shí)1ms DelayMs(1),去掉與加上,對計(jì)時(shí)沒有影響; 2:將中斷程序改成
voidTimer0_isr(void) interrupt 1
{
static unsigned char count=0;
count++;
if(count==50)
{
miao++;
count=0;
}
DelayMs(1);
TH0=(65536-2000)/256; //重新賦值 2ms
TL0=(65536-2000)%256;
}
影響結(jié)果很大! 為了再次驗(yàn)證樓主的想法,干脆將中斷程序改為
voidTimer0_isr(void) interrupt 1
{
static unsigned char count=0;
//TH0=(65536-2000)/256; //重新賦值 2ms
//TL0=(65536-2000)%256;
count++;
if(count==50)
{
miao++;
count=0;
}
DelayMs(1);
}
去掉重新賦值,計(jì)時(shí)依然,但是慢了許多! 結(jié)論:
1:定時(shí)計(jì)數(shù)滿了以后,模式1就是到達(dá)65536,溢出標(biāo)志TF0在進(jìn)入中斷服務(wù)程序后,自動(dòng)清零,開始下一次中斷計(jì)時(shí),計(jì)時(shí)是從中斷服務(wù)程序的第一條語句開始
2:正因?yàn)?,所以進(jìn)入中斷后,首先是給定時(shí)器賦值,否則其從0開始計(jì)時(shí),所以賦值的位置不對,結(jié)果差異很大
3:在中斷服務(wù)程序中是不會(huì)再次進(jìn)入此中斷,上面DelayMs(1)延時(shí)1MS沒有影響,但是一旦改成延時(shí)2ms,結(jié)果就亂了套,因此中斷服務(wù)的運(yùn)行時(shí)間不能超過定時(shí)器的定時(shí)時(shí)間,除非關(guān)閉中斷,最后再開啟中斷
以上是個(gè)人想法!
|