51 MCU Timer (learning)

It is important to understand the timer structure and functions , timing values calculated.

1. Understand the structure of the timer:

The essence of the timer/counter is an increment counter (16 bits), which consists of the **high 8 bits (TH) and lower 8 bits (TL)** two registers THx and TLx. TMOD is the working mode register of the timer/counter, which determines the working mode and function; TCON is the control register, which controls the start and stop of T0 and T1 and sets the overflow flag.

1. Working mode register TMOD The
working mode register TMOD is used to set the working mode of the timer/counter. The low four bits are used for T0 and the high four bits are used for T1. The format is as follows: generally use TMOD = 0x01 ; that is, working mode 1 , and you just need to know about other working modes.

Then there is C/T: timing/counting mode selection bit. C/T =0 is the timing mode, C/T =1 is the counting mode .


Insert picture description here
Insert picture description here

2. Calculate the initial value of the timer,

- 定时器模式时有:N=t/ T
计数初值计算的公式为:X=2^13-N = 65536 - N。
定时器的初值还可以采用计数个数直接取补法获得
- 外接晶振为12MHz→重要之处时,51单片机相关周期的具体值为:
振荡周期=1/12us;
状态周期=1/6us;
机器周期=1us;→重要之处
指令周期=1~4us;

Specific can refer to

1.晶振12M 
         12MHz除121MHz,也就是说一秒=1000000次机器周期。50ms=50000次 机器周期。   

         65536-50000=15536(3cb0) 

         TH0=0x3c,TL0=0xb0

   2.晶振11.0592M 

        11.0592MHz除12921600Hz,就是一秒921600次机器周期,50ms=46080次机器周期。 

        65536-46080=19456(4c00) 
        TH0=0x4c,TL0=0x00

1ms/1us=1000。

That is to count 1000 numbers, the initial value = 65535-1000+1 (because the counter actually counts to 66636 before it overflows) 64536=FC18H

3. Procedure

The following program first calculates the machine cycle of 50 milliseconds, and then *20 is the cycle of 1s. The specific code is as follows


#include<REG52.h>

typedef unsigned char u8;
typedef unsigned int u16 ;

sbit pt1 = P2^1;
sbit pt2 = P2^6;

u16 i ;
//初始化定时器喝中断
void InitMiddle_T()
{
    
    
	ET0 = 1;
	EA = 1;   
	TR0 = 1;
	
	TMOD = 0x01; 
  TH0 = 0x4c;
	TL0 = 0x00;
	
}

//主函数
void main()
{
    
    
	pt2 = 0;
	InitMiddle_T();
	
	while(1);
}

//中断函数
void Time() interrupt 1
{
    
    
	
  TH0 = 0x4c;
	TL0 = 0x00;
	i++;
	if(i == 20)
	{
    
    
		i =0;
		pt1 =~ pt1;
		pt2 =~ pt2;
	}
}

Guess you like

Origin blog.csdn.net/Msyusheng/article/details/115026166