Posted on Leave a comment

At89s52

 

8051 Timer/Counter, led 16×2

#include <REGX51.H> /* by Hoang N Tran*/
/* P1 port as data port, P2_0,1,2 pins to RS, RW, E pins of LCD16x2*/
void delay(int time){/*Use crystal 12MHz to make delay 1ms */
while(time–){
TMOD=0x01;
TH0=0xFC;
TL0=0x18;
TR0=1;
while(!TF0);
TF0=0;
TR0=0;
}
}

void LCD_Command (unsigned char cmd) /* LCD16x2 command funtion */
{
P1= cmd;
P2_0=0; /* command reg. */
P2_1=0; /* Write operation */
P2_2=1;
delay(1);
P2_2=0;
delay(5);
}

void LCD_Char (unsigned char char_data) /* LCD data write function */
{
P1=char_data;
P2_0=1; /* Data reg.*/
P2_1=0; /* Write operation*/
P2_2=1;
delay(1);
P2_2=0;
delay(5);
}

void LCD_String (unsigned char *str) /* Send string to LCD function */
{
int i;
for(i=0;str[i]!=0;i++) /* Send each char of string till the NULL */
{
LCD_Char (str[i]); /* Call LCD data write */
}
}

void LCD_Init (void) /* LCD Initialize function */
{
delay(10); /* LCD Power ON Initialization time about 10ms */
LCD_Command (0x38); /* Initialization of 16X2 LCD in 8bit mode */
LCD_Command (0x0C); /* Display ON Cursor OFF */
LCD_Command (0x06); /* Auto Increment cursor */
LCD_Command (0x01); /* clear display */
LCD_Command (0x80); /* cursor at home position */
}

void main(){
char h[8]=”00:00:00″;/* create a string variable for clock */
LCD_Init(); /* initialization of LCD*/
LCD_String(“Hello Khanh”); /* write string on 1st line of LCD*/
while(1){h[7]++;/* Infinite loop. */
if(h[7]==58){h[7]=48;h[6]++;}
if(h[6]==54||P2_7==0){h[6]=48;h[4]++;}
if(h[4]==58){h[4]=48;h[3]++;}
if(h[3]==54||P2_3==0){h[3]=48;h[1]++;}
if(h[1]==58){h[1]=48;h[0]++;}
if(h[0]==50&&h[1]==52){h[0]=48;h[1]=48;}
LCD_Command(0xC0);/* write string on 2nd line of LCD*/
LCD_String(h);
delay(1000);

}

}

 

  Explanation:

    timer clock frequency=  12 Mhz/12  = 1 Mhz.

    1 cycle need  1s/106 cycles= 10-6 s,  delay 1ms to need 1ms/time of 1 cycle=103 cycles.

    16 bits time mode 1 need 65536-1000=64536=FC18 cycles to overflows.

  How to value exactly for TH, TL:

    step1 : load FC18 to TH0=FC, TL0=18.

     for ex: observe in 24h, clock run slow 24m => 1ms slow 1/60×103 s.

       => 1ms slow 1/60×103/10-6 = 16.66 cycles.

    step 2 : need time mode 1 faster 17 cycles.

        65536-1000 +17=64519=FC07,  reload FC07 to TH0=FC, TL0=29.

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *