# why it dose not work (timer0 in 18f452)

#### mhghost

Joined May 16, 2013
6
hi i am a beginner with micro so i wanted to try to build a clock and here is the code

Rich (BB code):
sbit LCD_RS at RB4_bit;
sbit LCD_EN at RB5_bit;
sbit LCD_D4 at RB0_bit;
sbit LCD_D5 at RB1_bit;
sbit LCD_D6 at RB2_bit;
sbit LCD_D7 at RB3_bit;

sbit LCD_RS_Direction at TRISB4_bit;
sbit LCD_EN_Direction at TRISB5_bit;
sbit LCD_D4_Direction at TRISB0_bit;
sbit LCD_D5_Direction at TRISB1_bit;
sbit LCD_D6_Direction at TRISB2_bit;
sbit LCD_D7_Direction at TRISB3_bit;

char txt2[10];
char txt1[10];
int  x=0;
int y=0;
void main(){lcd_cmd( _LCD_CURSOR_OFF);
TRISB =0;
T0CON =0b10001111;
Lcd_Init();
while(tmr0h < 0b000011111){}
while(tmr0l < 0b01000011){}
x++;
T0CON =0b00001111;
tmr0h=0;
tmr0l=0;
if(x==60){x=0;y++;}
lcd_out (1,1,"time is ");
inttostr(x,txt1);
inttostr(y,txt2);
ltrim(txt1);
ltrim(txt2);
lcd_out(2,1,"m=");
lcd_out_cp(txt2);
lcd_out(2,9,"s=");
lcd_out_cp(txt1);

}
i don't know what is wrong but every time i come near a timer i mess up could some one please help me i am using a 18f452 pic and a 4 MHz cristeal

Last edited by a moderator:

#### mhghost

Joined May 16, 2013
6
can any one help me please

#### THE_RB

Joined Feb 11, 2008
5,438

I think the very first thing you need to do is work out HOW to get exact seconds, and make sure that works.

Personally I prefer the simplicity and tunability of a Bresenham type system, which can make perfect seconds from any xtal speed.

http://romanblack.com/one_sec.htm

Here is one, to give actual seconds from a TMR0 and your 4MHz xtal;
Rich (BB code):
  // uses 1 variable; unsigned long bres
// gets here every TMR0 int (every 256 ticks)

bres += 256;         // add 256 ticks to bresenham total

if(bres >= 1000000)  // if reached 1 second!
{
bres -= 1000000;   // subtract 1 second, retain error
do_1sec_event();   // update clock, etc
}
That code goes inside your TMR0 overflow interrupt, and TMR0 prescaler set to 1:1.

For now I would concentrate on getting the interrupt and that code working, and just make it toggle a LED every second.

Then you can compare that to a household clock, and if the flashing LED is keeping good time you can then add more code, to count seconds and minutes.