#include <xc.h>

#define _XTAL_FREQ 20000000UL

/* Timer0 delay of 500 ms
   Fosc = 20 MHz  ->  Timer clock = Fosc/4 = 5 MHz
   Prescaler 1:256 -> 1 tick = 256 / 5 MHz = 51.2 us
   Counts needed  = 500 ms / 51.2 us = 9766
   Preload value  = 65536 - 9766 = 55770 = 0xD9DA          */
void Timer0_Delay_500ms(void)
{
    TMR0H = 0xD9;               // load high byte first
    TMR0L = 0xDA;               // then low byte
    INTCONbits.TMR0IF = 0;      // clear overflow flag
    T0CONbits.TMR0ON = 1;       // start timer

    while(INTCONbits.TMR0IF == 0);   // wait for overflow

    T0CONbits.TMR0ON = 0;       // stop timer
    INTCONbits.TMR0IF = 0;      // clear flag
}

void main(void)
{
    ADCON1 = 0x0F;              // make pins digital

    TRISB = 0x00;               // PORTB = output (LEDs)
    LATB  = 0x00;               // all LEDs OFF

    T0CON = 0x07;               // 16-bit, internal clock, prescaler 1:256, timer OFF

    while(1)
    {
        LATBbits.LATB0 = !LATBbits.LATB0;   // toggle LED1 (RB0)
        Timer0_Delay_500ms();
    }
}
