之前我們一直用的是軟件延時,不是很精確
16 位 是 兩個字節(jié) TH 和 TL
TH 和 TL 可以放初值
軟件延時占用cpu資源,而定時器不占用棒拂。
時鐘周期 = 1/晶振頻率
機(jī)器周期 = 12*時鐘周期
![Uploading Paste_Image_491757.png . . .]
定時器每經(jīng)過一個機(jī)器周期加一
定時器和計數(shù)器其實是一體的倒谷,不過是通過TMOD來設(shè)置的
假設(shè)要定時器0工作模式1
TMOD = 0x01;
定時器1 工作模式1
TMOD=0x10;
定時50ms
實際上也可以這樣寫
50ms就是 a = 50ms /(1.085 *10^6)
TH = (65536 - (a) )/256
TL = (65536 -(a))%256
顯示0-60的每妙加一
#include<reg52.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit we = P2^7;
sbit du = P2^6;
sbit LED1 = P1^0;
uchar counter,time_counter;
uchar code leddata[]={
0x3F, //"0"
0x06, //"1"
0x5B, //"2"
0x4F, //"3"
0x66, //"4"
0x6D, //"5"
0x7D, //"6"
0x07, //"7"
0x7F, //"8"
0x6F, //"9"
0x77, //"A"
0x7C, //"B"
0x39, //"C"
0x5E, //"D"
0x79, //"E"
0x71, //"F"
0x76, //"H"
0x38, //"L"
0x37, //"n"
0x3E, //"u"
0x73, //"P"
0x5C, //"o"
0x40, //"-"
0x00, //熄滅
0x00 //自定義
};
void delay(uint z)
{
uint x,y;
for(x = z; x>0; x--)
for(y = 114;y>0;y--);
}
void display(uchar i)
{
uchar shi,ge;
shi = i/10;
ge = i%10;
P0 = 0xff;
we = 1;
P0 = 0xfe;
we = 0;
du = 1;
P0 = leddata[shi];
du = 0;
delay(1);
P0 = 0xff;
we = 1;
P0 = 0xfd;
we = 0;
du = 1;
P0 = leddata[ge];
du = 0;
delay(1);
}
int main()
{
TMOD = 0x01;
TH0 = (65536-46082)/256;
TL0 = (65536-46082)%256;
TR0 = 1;
while(1)
{
if(TF0==1)
{
TF0 = 0;
TH0 = 0x4b;
TL0 = 0xfe;
counter++;
}
if(counter == 20)
{
counter = 0;
LED1 = ~LED1;
time_counter++;
}
if(time_counter==60)
{
time_counter = 0;
}
display(time_counter);
}
return 0;
}