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 */ void LCD_Char (unsigned char char_data) /* LCD data write function */ void LCD_String (unsigned char *str) /* Send string to LCD function */ void LCD_Init (void) /* LCD Initialize function */ void main(){ } } |
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.