之前我们一直用的是软件延时,不是很精确
16 位 是 两个字节 TH 和 TL
TH 和 TL 可以放初值
软件延时占用cpu资源,而定时器不占用。
时钟周期 = 1/晶振频率
机器周期 = 12*时钟周期
![Uploading Paste_Image_491757.png . . .]
定时器每经过一个机器周期加一
定时器和计数器其实是一体的,不过是通过TMOD来设置的
假设要定时器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;
}