# PIC16F877A Timer0 delay problem?

To get min 5ms square wave. I chosen prescalar as 1:32 (The internal clock given 4Mhz), what will be the TMR0 register value? Is it 0x64 or 0x63 !!

• This will depend on your oscillator frequency. More details needed. Nov 19, 2014 at 4:42
• Added main frequency.(4 Mhz) Nov 19, 2014 at 4:44
• I have edited my answer to your question with a 4Mhz frequency. Nov 19, 2014 at 6:42
• Check your answer again. Nov 19, 2014 at 7:48
• At 4MHz, you can get either 496 or 504us, not 500 exactly. Nov 19, 2014 at 14:00

## 2 Answers

By my calcs, with a 4MHz system clock, and a 1MHz timer clock, and a prescaler of 32, that's a tick frequency of 31250 Hz. Your tick time is 32 microseconds. To count to 0.005 seconds, your need 156.25 clock ticks. Round up to 0x9D.

So, you can set the timer to 0, wait until it reaches 0x9D, toggle your bit, then reset to 0.

Another way to do this would be to preset the timer to 0xFF-0x9D, and enable the interrupt. The interrupt, triggered when the timer rolls over from 0xFF to 0x00 would toggle your bit, and reset the timer to 0xFF-0x9D. (or more accurately 0xFF-0x9D+the current value of the timer, which hasn't stopped during the interrupt)

• Ok my case is 5ms so 0x63 or 0x64 better. Nov 19, 2014 at 15:57
• 0x9D by my calc. Nov 19, 2014 at 17:15

What is your main clock frequency? If it is 20MHz, to get .5ms with a prescale of 32, it needs to count to 313. I would suggest a prescale of 64 and look for the TMR0 value to exceed 0x9C, so you do not need to count overflow.

This is how to do the calculation, it is simple:

Timer Clock (Hz) = Clock Frequency / Prescale

Timer Tick (Seconds) = 1 / Timer Clock

Timer Ticks Needed (Integer) = .5ms / Timer Tick

--- EDIT after frequency provided

Look for the register value to exceed 0x3F if you want .504ms, and 0x3E if you want .496ms. That is as accurate as it gets with your configuration.

• Frequency is 4Mhz Nov 19, 2014 at 4:40
• I'm not getting .504ms when I multiply 0x3F with 1:32 prescalar. Nov 19, 2014 at 7:48
• You are not supposed to multiply it with the prescalar, you are supposed to multiply it by the time of one timer tick. Look at the equations I posted. Nov 19, 2014 at 15:03
• Note that the TIMER clock is the SYSCLOCK/4 -- i.e., if your system clock is 4 MHz, your timer clock is 1 MHz Nov 19, 2014 at 15:35
• @VijithaStephy Helping you would be easier if you told us what you DID see along with what you DIDN'T Nov 19, 2014 at 15:35