51单片机入门04--定时&计数器

Catalogue
  1. 1. 51单片机入门04–定时&计数器
    1. 1.1. 原理
      1. 1.1.1. 工作方式

51单片机入门04–定时&计数器

原理

image-20200520204754535

常用的工作方式是1(16位)和2(8位自动重置,用于串口通信产生波特率)

一般用的是工作方式1

image-20200520205107854

GATE一般给0,如果通过外部中断来启用定时计数器,可以给1

image-20200520205329831

工作方式

image-20200520205738730

单片机定时器单位是us,1ms=1000us

11.0592MHz用于通讯

image-20200528214728882

例:使用定时器显示数字,每秒一变

image-20200529072341040

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
#include "reg51.h"
unsigned char num[] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
int n = 0;
int count = 0;
void inittimer(){
TMOD = 0x01; //0000 0001
TH0 = (65536-50000)/256;//16位定时初值高8位
TL0 = (65536-50000)%256;
ET0 = 1;//开启定时器0中断
EA = 1; //开启总中断
TR0 = 1; //开启定时器0
}

void display(){
P2 = num[n];
if(n == 10){
n = 0;
}
}

void main(){
inittimer();
while(1){
display();
}
}

void timer_isr() interrupt 1{
TH0 = (65536-50000)/256; //50us
TL0 = (65536-50000)%256;
count++;
if(count==20){
n++;
count=0;
}
}

示例:计数器

image-20200529072849386

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
#include "reg51.h"
unsigned char num[] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
int n=0;

void initcounter(){
TMOD = 0x06;
TH0 = 256 - 1;
TL0 = TH0;
ET0 =1;
EA =1;
TR0 =1;
}

void display(){
P2 = num[n];
if(n == 10)n=0;
}

void main(){
initcounter();
while(1){
display();
}
}

void counter_isr() interrupt 1{
n++;
}