/*******************************************************************************
* Program:
*    Buffered Input Sample Program (getbufin.c)
*    Technologic Systems TS-7350/70/90/95 
* Summary: 
*    This example program demonstrates the ability to monitor buffered input 
* pins through c programming.  Only dedicated input pins IN_00 through IN_06 are
* utilized here.  Be sure the connection is made before running this program
* otherwise you will get "junk".
*
* Example Usage:
*   ts7000:~# ./getbufin2 1
*   Buffered Input Value on IN_01: 1
* 
* Compile with: 
*    gcc -mcpu=arm9 -o getbufin getbufin.c
*
* Hardware Notes:
*    JTAG/DIO Header Pin-Out
*
*    + + + + 3 + + + 0 + + + + + + + + x x x 
*    + + + + + + + + + + 0 1 2 3 4 5 6 + + + 
*    | JTAG         | DIO                   |
*
*    Pin marked with 3 is 3.3V
*    Pin marked with 0 is GND
*    Pins marked with 0-6 are Buffered Inputs IN_00, ..., IN06
*    Pins marked with x are shared with ADC
*    Note: Pin IN_00 is above and slightly right of the white dot 
*          on the TS-9445 JTAG Header
*******************************************************************************/
#include<unistd.h>
#include<sys/types.h>
#include<sys/mman.h>
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<string.h>
#include<assert.h>

/**************************************************
* Main  
***************************************************/
int main(int argc, char **argv)
{
   volatile unsigned int *BUFIN;
   unsigned int state;
   unsigned char *start;
   int fd = open("/dev/mem", O_RDWR|O_SYNC);
   int pinoffset;
   int pin_name;  //IN_00 is 0, IN_01 is 1, IN_02 is 2, etc...

   // Check for invalid command line arguments
   if (argc != 2) 
   {
       printf("Usage: %s <pin_name>\n", argv[0]);
       return 1;
   }
   

   // Read buffered input register from mmap (pagesize boundaries required) 
   start = mmap(0, getpagesize(), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 
           0x600FF000);  // From TS-7350 Manual "Buffered Inputs"
   
   // BUFFERED INPUTS
   BUFIN = (unsigned int *)(start + 0x84);  // Correct for pagesize (4096 byte)
                                            // boundaries.
   // read state of pins
   state = *BUFIN; 
   
   // Gather pin name from the command line argument and check for invalid
   pin_name = strtoul(argv[1], NULL, 0);
   assert(pin_name <=6 && pin_name >=0);
   
   // Pins IN_00 through IN_06 are accessed by bits 7 through 13. 
   pinoffset = pin_name + 7;

   // Print the results   
   printf("Buffered Input Value on IN_0%d: %d\n", pin_name, (state >> 
   (pinoffset)) & 0x1);
   
   return 0;
}

