Timer0 Register Low Byte and high byte(PIC18f4550)

Thread Starter

khatus

Joined Jul 2, 2018
85
This is the code generated by mikroC timer calculator for 10 ms delay using timer0 ( I'm using pic18f4550)
//Timer0
//Prescaler 1:1; TMR0 Preload = 15536; Actual Interrupt Time : 10 ms

//Place/Copy this part in declaration section
void InitTimer0()
{
T0CON = 0x88;
TMR0H = 0x3C;
TMR0L = 0xB0;
GIE_bit = 1;
TMR0IE_bit = 1;
}

void Interrupt()
{
if (TMR0IF_bit){
TMR0IF_bit = 0;
TMR0H = 0x3C;
TMR0L = 0xB0;
//Enter your code here
}
}

My question is why Timer0 Register Low Byte and high byte is mentioned two times
1. inside InitTimer0() function??
2. Inside Interrupt() function??
 

AlbertHall

Joined Jun 4, 2014
10,068
So that the first interrupt will be after the same delay as all the others.
Without that setting in InitTimer0() the first interrupt time is indeterminate.
 

spinnaker

Joined Oct 29, 2009
7,835
This is the code generated by mikroC timer calculator for 10 ms delay using timer0 ( I'm using pic18f4550)
//Timer0
//Prescaler 1:1; TMR0 Preload = 15536; Actual Interrupt Time : 10 ms

//Place/Copy this part in declaration section
void InitTimer0()
{
T0CON = 0x88;
TMR0H = 0x3C;
TMR0L = 0xB0;
GIE_bit = 1;
TMR0IE_bit = 1;
}

void Interrupt()
{
if (TMR0IF_bit){
TMR0IF_bit = 0;
TMR0H = 0x3C;
TMR0L = 0xB0;
//Enter your code here
}
}

My question is why Timer0 Register Low Byte and high byte is mentioned two times
1. inside InitTimer0() function??
2. Inside Interrupt() function??

The register counts down to zero (if memory serves) and the interrupt is triggered. So the register needs to be loaded again with the required interrupt time inside the interrupt. Been away from this for a while so can't remember for sure if it counts up or down but either way it needs to be reset.

What I do is to set a #define macro, so if I need to change the value, I don't need to remember to do it in two places.

Example

Code:
#define  TMR0H_VAL   0x3C
#define TMR0L_VAL  0xB0


[B]void InitTimer0()[/B]
{
T0CON = 0x88;
TMR0H =TMR0H_VAL;
TMR0L =TMR0L_VAL;
GIE_bit = 1;
TMR0IE_bit = 1;
}

[B]void Interrupt()[/B]
{
if (TMR0IF_bit){
TMR0IF_bit = 0;
TMR0H = TMR0H_VAL;
TMR0L =TMR0L_VAL;
//Enter your code here
}

/[code]
 

spinnaker

Joined Oct 29, 2009
7,835
It counts up and it is the rollover to zero which sets the interrupt flag.

Thanks for refreshing my memory. After I posted I had thought I had gotten it backward.

But either way since it reaches zero the register needs to be set initially and every time the interrupt occurs.
 
Top