/*
	UINVDVR.C

   PK21xx/Rugged Giant (only) sample program that illustrates selectively
   reading the state of the seven universal inputs with the keypad.
   
   - the state is a 1 if the input voltage is above UiHIGH
   - the state is a 0 if the input voltage is below UiLOW
   - UiHIGH and UiLOW for any channel can be set in software
   - select the channel with the keypad
*/

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

#if !(BOARD_TYPE==CPLC_BOARD)
#fatal "This program only runs on a PK21xx/Rugged Giant"
#endif

main()
{
    int  k, oldk;
    int  newuin, olduin;
    
    uplc_init();

    lcd_printf(0x00000100L, "Hello World");
              // set high trigger at 5.5 volt
              // set low trigger at 4.5 volt
              // you can use the watch window to change these values
              // up_uncal convert the desired voltage to raw calibrated value

    for (k = 0; k < 7; k++)
    {
        *(&U1HIGH + 3 * k) = up_uncal(5500);
        *(&U1LOW  + 3 * k) = up_uncal(4500);
    }

    printf("%d %d %d %d %d %d %d\n", 
    U1HIGH, U2HIGH, U3HIGH, U4HIGH, U5HIGH, U6HIGH, U7HIGH);
    
    printf("%d %d %d %d %d %d %d\n", 
    U1LOW, U2LOW, U3LOW, U4LOW, U5LOW, U6LOW, U7LOW);

    oldk = k = 1;

    while (1)
    {
        if (lc_kxget(1) < 0) 
            runwatch();      // wait for a key
        else                 // runwatch allows monitoring with the
                             // watch window
        {
            k = lc_kxget(0); // get key out of the buffer
            if (k > 7) 
                k = 7;       // only seven channels available
            up_beep(100);
        }
        newuin = *(&U1IN + 6 * (k - 1));
        if ((newuin != olduin) || (oldk != k))
        {
            showuidigin(k, newuin);
            olduin = newuin;
            oldk   = k;
        }
    }
}

int showuidigin(int chan, int digvalue)
{
    char *onoff[] =
     {
         "OFF", "ON"
     };

    lcd_erase_line(1);
    lcd_printf(0x01000000L, "Input %d is %s", chan, onoff[digvalue]);
    printf("Input %d is %s\n", chan, onoff[digvalue]);
}
