/*
	PRT0DEMO.C
	
   PK21xx/Rugged Giant and PK22xx/Little Star Sample Program illustrating the
	use of PRT0 (programmable reload timer 0 ) for periodic interrupts.

   While running, use the runwatch window to monitor the value of PRTCounter.
*/

#use "default.h"
#use cplc.lib

#if !(BOARD_TYPE==CPLC_BOARD || BOARD_TYPE==L_STAR)
#fatal "This program only runs on a PK21xx/Rugged Giant or a PK22xx/Little Star"
#endif

int PRTCounter;

main()
{
    uplc_init();
    PRTCounter = 0;

#if BOARD_TYPE==CPLC_BOARD
    prt0_init(3072);         // interrupt every 10 ms
                             //  i.e. (3072*20)/6.144Mhz = 10 ms
#elif BOARD_TYPE==L_STAR
    if (sysclock() == 0x3c00) 
        prt0_init(9216);
                             // interrupt every 10 ms
                             // i.e. (9216*20)/18.432Mhz = 10 ms
    else 
        prt0_init(4608);
                             // interrupt every 10 ms
                             // i.e. (4608*20)/9.216Mhz = 10ms
#endif

    while (1)
    {
        while (PRTCounter < 1000) 
            runwatch();      // count for 10 secs then print
        PRTCounter = 0;
        printf("Time out\n");
    }
}


#INT_VEC PRT0_VEC ccc        // set interrupt vector for interrupt routine

interrupt reti int ccc()
{
    inport(TCR);
    inport(TMDR0L);          // clear TIF
    EI();
    ++PRTCounter;
}

#define TDE0  0
#define TIE0  4

int prt0_init(int tc)
{
    IRES(TCR, TDE0);         // disable count down
    IRES(TCR, TIE0);         // disable interrupts
    outport(TMDR0L, tc);
    outport(TMDR0H, tc >> 8);// set data reg
    outport(RLDR0H, tc >> 8);// set reload counter to value
    outport(RLDR0L, tc);     // set reload counter to value
    ISET(TCR, TDE0);         // enable count down
    ISET(TCR, TIE0);         // enable interrupts
    EI();
}
