I am trying to write a subroutine that generates a delay of 1000 ms using the Timer1 of the PIC18F4321 in 16-bit mode in MPLAB X IDE with XC8 compiler. This delay is exploited to toggle a LED. My problem is that I can't get the delay wanted (1000 ms). I tried to debug the program I observed that the value of "count" calculated using the macro is not correct. it gives a value of 0x4000 rather than 0x0F42. I don't know what is wrong with the macro:
#define count (((timeDelay) * 1000) / (timerPeriod) * 256)
// C-program using polled I/O:
#include <P18F4321.h>
#define timeDelay (1000) // 1000 ms
#define Fosc (4) // 4 MHz
#define timerPeriod (1 / ((Fosc) / 4)) // us
#define count (((timeDelay) * 1000) / (timerPeriod) * 256)
#define countInit ((0xFFFF - (count)) + 1)
#define countInitHigh ((countInit & 0xFF00) >> 8)
#define countInitLow (countInit & 0x00FF)
void T0Delay(); // A subroutine that generates a delay of 1000 ms
void main()
{
OSCCON = 0x60; // 4MHz Internal Oscillator
TRISC = 0x00; // Port C output
T0CON = 0x07; // 16-bit, 1:256 prescaler, internal clock
for(;;) // loop forever
{
PORTCbits.RC0 = 0; // turn LED OFF
T0Delay(); // Wait 10 seconds
PORTCbits.RC0 = 1; // turn LED ON
T0Delay(); // Wait 10 seconds
}
}
void T0Delay(void)
{
TMR0H = countInitHigh;
TMR0L = countInitLow;
INTCONbits.TMR0IF = 0; // clear timer overflow flag
T0CONbits.TMR0ON = 1; // start Timer0
while(!INTCONbits.TMR0IF); //polling, wait until timer finishes counting
T0CONbits.TMR0ON = 0; // Stop Timer0
}