51单片机定时器

1、定时器介绍

定时器介绍:51单片机的定时器属于单片机的内部资源,其电路的连接和运转均在单片机内部完成
定时器作用:

  • (1)用于计时系统,可实现软件计时,或者使程序每隔一固定时间完成一项操作
  • (2)替代长时间的Delay,提高CPU的运行效率和处理速度

STC89C52芯片的定时器个数:3个(T0、T1、T2),T0和T1与传统的51单片机兼容,T2是此型号单片机增加的资源

注意:定时器的资源和单片机的型号是关联在一起的,不同的型号可能会有不同的定时器个数和操作方式,但一般来说,T0和T1的操作方式是所有51单片机所共有的(每个51型号的单片机一定都会有T0,T1两个定时器,在此基础上不同芯片再会增加定时器的个数)

2、定时器框图

定时器触发序号:

3、定时器重要寄存器

4、定时器控制LED亮灭

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <REGX52.H>

unsigned int cnt=0;

void Timer0_Init(){
TMOD=0x01;
TF0=0;
TR0=1;
ET0=1;
EA=1;
TH0=(65535-1000)/256;
TL0=(65535-1000)%256;
PT0=0; //这句代码在配置中断优先级,这个可加可不加,因为在这里不涉及到多个优先级的设置
}

void main(){
Timer0_Init();
while(1){

}
}

void Timer0_Interrupt() interrupt 1
{
TH0=(65535-1000)/256;
TL0=(65535-1000)%256;
cnt++;
if(cnt==1000){
cnt=0;
P2_0=~P2_0;
}
}

5、用STC-ISP生成定时器初始化函数

可以按一下配置来生成一段常用的定时器初始化函数代码:

使用STC-ISP生成后的代码更新如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <REGX52.H>

unsigned int cnt=0;

void Timer0_Init(void) //1毫秒@12.000MHz
{
TMOD &= 0xF0; //设置定时器模式
TMOD |= 0x01; //设置定时器模式
TL0 = 0x18; //设置定时初值
TH0 = 0xFC; //设置定时初值
TF0 = 0; //清除TF0标志
TR0 = 1; //定时器0开始计时
ET0=1;
EA=1;
PT0=0;
}

void main(){
Timer0_Init();
while(1){

}
}

void Timer0_Interrupt() interrupt 1
{
TL0 = 0x18; //设置定时初值
TH0 = 0xFC; //设置定时初值
cnt++;
if(cnt==1000){
cnt=0;
P2_0=~P2_0;
}
}

6、定时器实现时钟

实现代码:
Timer0.h:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include "Timer0.h"
#include <REGX52.H>

void Timer0Init(void) //1毫秒@12.000MHz
{
TMOD &= 0xF0; //设置定时器模式
TMOD |= 0x01; //设置定时器模式
TL0 = 0x18; //设置定时初值
TH0 = 0xFC; //设置定时初值
TF0 = 0; //清除TF0标志
TR0 = 1; //定时器0开始计时
ET0=1;
EA=1;
PT0=0;
}

main.c:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <REGX52.H>
#include "Timer0.h"
#include "LCD1602.h"

unsigned int cnt=0;
unsigned char hour,min,sec;

void main(){
Timer0Init();
LCD_Init();
LCD_ShowString(1,1,"Clock:");
LCD_ShowString(2,1," : : ");
while(1){
LCD_ShowNum(2,1,hour,2);
LCD_ShowNum(2,4,min,2);
LCD_ShowNum(2,7,sec,2);
}
}

void Timer0_Interrupt() interrupt 1
{
TL0 = 0x18; //设置定时初值
TH0 = 0xFC; //设置定时初值
cnt++;
if(cnt==1000){
cnt=0;
sec++;
if(sec==60){
min++;
if(min==60){
hour++;
if(hour==24){
hour=0;
}
}
}
}
}

51单片机定时器
http://example.com/2025/05/10/51单片机定时器/
Author
John Doe
Posted on
May 10, 2025
Licensed under