#use "default.h"

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

/*
	GENINT2.C

   Sample program that illustrates a use of the /INT2 interrupt line.
   
   Connect /USER3 to /INT2 on H4 (pin 5 to pin 8) to generate negative
   pulses to trigger INT2.
   
   Type "pulse(50)" in the watch window to begin generating interrupts.
   Try different values of the argument to change the number of pulses
   generated.
   
   Type "set_int2(100)" in the watch window to reload the int2 interrupt
   counter. Try different values of the argument to change the maximum
   number of interrupts to count.
*/

int testcnt2;
int maxcount;
int int2_flag;

void pulse(int count);
void set_int2(int count);

main()
{
int testcntold;

    set_int2(100);              // set to count 100 interrupts
    
    testcntold = !testcnt2;

    while(1)
    {
        runwatch();
        if( testcntold != testcnt2)
        {
            testcntold = testcnt2;
            printf("Interrupts generated >> %d\n", testcntold);
        }
        if( int2_flag)
        {
            int2_flag = 0;
            printf("Finish counting %d interrupts.\n", testcnt2);
        }
    }
}

// Artificial negative pulse generator to drive /INT2 for this sample.

void pulse(int count)
{
    int i;
    for(i=0;i<count;i++)
        outport(USER3, 0xff);       // data is irrelevant since /USER3 is
                                    // a control line.
}

// Set the interrupt service routine to count this number of interrupts.

void set_int2(int count)
{
   DI();
   int2_flag = 0;
   testcnt2 = 0;
   maxcount = count;
   ISET(ITC, 2);        // enable INT2 interrupt
   EI();
}

#INT_VEC INT2_VEC int2test

interrupt reti int2test()
{
    if(++testcnt2 == maxcount)
    {
      IRES(ITC, 2);     // disable INT2 interrupt
      int2_flag = 1;    // int2_flag is set to let main program know
    }
}