#use "default.h"

#if (BOARD_TYPE!=LittleG)
#fatal "This program only runs on the BL16xx/LittleG."
#endif

/*
	GENPRT0.C

   Uses PRT0 (programmable reload timer 0 ) for generating periodic
   interrupts.

   Every 100ms, the states of the digital inputs IN06 to IN11 ( up_digin(7)
   to up_digin(12) ) are monitored. The reverse state of each input bit is
   sent out to HC1 to HC6 (up_setout(9,onoff) and up_setout(14, onoff),
   respectively.
*/

void monitor_lgn_io();
unsigned int PRTCounter;
int sec_count;
int sec_flag; 

main()
{
    PRTCounter = 0;
    sec_flag   = 0;
    sec_count  = 0;

    prt0_init(46080);        // interrupt every 100 ms
                             // i.e. (46080*20)/9.216Mhz = 100ms
    while (1)
    {
      if(sec_flag)
      {
         sec_flag = 0;
         printf("PrtCounter: %4d\r", PRTCounter);
      }
      runwatch();
    }
}

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

interrupt reti int ccc()
{
    inport(TCR);
    inport(TMDR0L);         // clear TIF
    PRTCounter++;
    sec_count++;
    if(sec_count==10)
    {
         sec_count = 0;
         sec_flag = 1;
    }
    EI();                   // enable interrupt before calling monitor_io.
    monitor_lgn_io();
}

#define TDE0  0
#define TIE0  4

int prt0_init(int tc)
{
    DI();                       
    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();
}

void monitor_lgn_io()
{
    up_setout(9, !up_digin(7));           // HC1 = !IN06
    up_setout(10, !up_digin(8));          // HC2 = !IN07 
    up_setout(11, !up_digin(9));          // HC3 = !IN08
    up_setout(12, !up_digin(10));         // HC4 = !IN09
    up_setout(13, !up_digin(11));         // HC5 = !IN10
    up_setout(14, !up_digin(12));         // HC6 = !IN11
}
