#include <xc.h>

#define _XTAL_FREQ 20000000UL

unsigned char count   = 0;      // 8-bit counter
unsigned char running = 0;      // 1 = counting, 0 = stopped
unsigned char ticks   = 0;      // counts 10 ms steps

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

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

    TRISAbits.TRISA2 = 1;       // RA2 = input (SW18, START)
    TRISAbits.TRISA3 = 1;       // RA3 = input (SW19, RESET)

    while(1)
    {
        // START button
        if(PORTAbits.RA2 == 0)
        {
            __delay_ms(30);                 // debounce
            if(PORTAbits.RA2 == 0)
            {
                running = 1;                // start counting
                while(PORTAbits.RA2 == 0);  // wait for release
            }
        }

        // RESET button
        if(PORTAbits.RA3 == 0)
        {
            __delay_ms(30);                 // debounce
            if(PORTAbits.RA3 == 0)
            {
                running = 0;                // stop counting
                count = 0x00;               // reset count
                ticks = 0;
                LATB = count;               // LEDs show 00H
                while(PORTAbits.RA3 == 0);  // wait for release
            }
        }

        // Up-counter: increment every 50 x 10 ms = 500 ms
        if(running == 1)
        {
            __delay_ms(10);
            ticks++;

            if(ticks >= 50)
            {
                ticks = 0;
                count++;                    // 00H -> FFH -> 00H ...
                LATB = count;               // show count on LEDs
            }
        }
    }
}
