51 MCU timer


Timing 1-second cascade calculation method:
    First, make clear 1. Mechanical cycle = 1/crystal frequency (12MHZ) * 12 = 1μS
             2. Understand the maximum time of calculation timing: 2^16 *1μS=65.536ms
             3. Calculate the 16-input corresponding to 50ms The control value is
                50ms/1μs=50000=0xC350
             4. Set the timer to work as 16bit 2^16= 0xFFFF
                Set the initial value: T0=0xFFFF-0xC350=0x3CAF, that is, start from this initial value and accumulate to the highest value, it will take 50ms
             5. Accumulate 20 50ms to get 1s timing period

   

#include<reg51.h>
//Common anode digital tube truth table
unsigned char code LedChar[]={
	0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92, 0x82, 0xF8,
	0x80, 0x90, 0x88, 0x83, 0xC6, 0xA1, 0x86, 0x8E
	};

void  main()
{
	unsigned int i=0;
    unsigned  char cnt=0;
	unsigned  int tcnt=0;
	TMOD = 0x01; //Set working mode
	TH0 = 0xB8; //Define the high byte of the initial value
	TL0 = 0x00; //Define the low byte of the initial value
	TR0 = 1; //Start counting from the initial value ++

	while(1)
	{
		if(TF0==1) // Accumulate from the initial value to the highest time 0xFFFF to trigger a TF0 overflow flag, first calculate how many machine cycles in 20ms, and convert it into hexadecimal,
		{
		  TF0=0;
		  TH0 = 0xB8;
		  TL0=0x00;
		  tcnt++;

		  if(tcnt>=50)
		  {
		  tcnt=0;
		    if(cnt<8)
		   {
			  P0=~(0x01<<cnt);		   //0000 0001->1111 1110		  0000 0010 ->1111 1101
			  P2=LedChar[cnt+1];
		   }     
		   else if(cnt>=8)
		   {
			  P0= ~(0x80>>(cnt-7));        //1000 0000->0111 1111
			  P2=LedChar[cnt-7];
		   }
		
		   cnt++;
	
			if(cnt>=15)
			{
			cnt=0;
			}	  
		  }	
		}	 
	}
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326615914&siteId=291194637