/*
 * rpi_ser_tcc.c - rs232 code to drive robot electronics ISS & MAX2719 module. 
 *  modified from MD49.c
 * 
 * robot electronics USB-ISS driving MAX2719 7Seg Display example code for raspberry pi.
 * 
 * PC/LINUX]---[USB_ISS]---[MAX2719 & 8 digit 7seg display ]
 * 
 * on LINUX:  gcc -Wall -o "%e" "%f"
 * on PC:     tcc %f
 * 
 * 
 * 
 * By James Henderson, 2012,
 * Modified Doug Rice 2014
 *
 * 
 * Useful documentation:-
 * http://en.wikibooks.org/wiki/Serial_Programming/termios
 *
 * Useful documentation about the IIC and ultrasound modules.
 * http://www.robot-electronics.co.uk/htm/raspberry_pi_examples.htm
 *
 * =======================
 * Ultra Sound SRF08 module
 * =======================
 * http://www.robot-electronics.co.uk/htm/usb_i2c_tech.htm
 * 
 * http://www.robot-electronics.co.uk/acatalog/Ultrasonic_Rangers.html
 * http://www.robot-electronics.co.uk/htm/srf02tech.htm
 * http://www.robot-electronics.co.uk/htm/srf02techI2C.htm
 *
 * =======================
 * ISS module and MAX2719
 * =======================
 * http://www.robot-electronics.co.uk/htm/usb_iss_tech.htm
 * http://www.robot-electronics.co.uk/htm/usb_iss_tech.htm#Response%20Bytes
 * MAX2719 7 seg dispaly chip
 * 
 * http://www.maximintegrated.com/en/products/power/display-power-control/MAX7219.html
 * 
 * 
 *  [LINUX ] --[USB_ISS]--[MAX2719]--[8x7seg display]
 * 
 * [LINUX] "/dev/ttyACM0" [USB_ISS]
 * 
 *  USB_ISS] --- [ MAX7219
 *   I/O:2 -------- CLK
 *   I/O:3 -------- DIN
 *   I/O:4 -------- /CS
 * 
 *  I needed to slug the lines with 0.1uf  capacitors.
 * =======================
 * LCD03 and LCD05 - I have LCD02
 * =======================
 * http://www.robot-electronics.co.uk/htm/Lcd03tech.htm
 * http://www.robot-electronics.co.uk/htm/Lcd05tech.htm
 * =======================
 * ISS module and MAX2719
 * =======================
 *
 *
 * ICC modules need:
 * GND		G
 * VCC		5
 * SCL		C
 * SDA		D
 * 
 * each module I own is different !!

 * 5v SDA SCL I/P  GND	IIC module

 * 5v SDA SCL mode GND	SRF08 Ultrasound module


 * 
 * 5v IO4 IO3 IO2 IO1 GND	ISS module IO_mode 0x00	
 * 5v SDI SCK SDO /CS GND	ISS module
 * 5v IO4 IO3 Tx  Rx  GND	ISS module
 * 5v SDA SCL IO2 IO1 GND	ISS module
 * 5v SDA SCL Tx  Rx  GND	ISS module
 
 * 5v SDA SCL GND 	Robot Electronics LCD02

 * G 5 C D 	OLED display

 * G 5 D C 		red Phillips Philips PCF8574 I/O chip.
 * G 5 D C SQW 32K	clock module
 * G 5 D C 		clock module
			

5 G C D
5 G D C

5 D C G
5 D G C

5 C D G
5 C G D


G 5 C D
G 5 D C

G C 5 D
G C D 5

G D 5 C
G D C 5

12 combinations x2 reversed

x2 reversed.

 */


/*
=============================================
Sec 1.0 
=============================================
*/

#ifdef __TINYC__ 
#define tcc 1
#endif


#ifdef linux
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <termios.h>
#include <errno.h>
#endif

#define	MAX2719_CLK 2
#define	MAX2719_DIN 4
#define	MAX2719_CS  8
#define	MAX2719_CLK_time  500

#ifdef linux
#define DELAY  usleep( MAX2719_CLK_time );
#define DELAYL usleep( 500000 );
#endif


#ifdef tcc

#include <conio.h>
#include <stdio.h>
#include <windows.h>
#include <time.h>
#define COM_PORT 6 // ////////// Modify as required.

#define DELAY 	;

#define DELAYM  delay_ms( 1 );
#define DELAYL delay_ms( 100 );

HANDLE rs_initialise (int io_port, const long int BaudRate, const char parity, const char data);
void rs_terminate(const int io_port);
// delay_routines
void delay_ms(clock_t millis);

HANDLE hCom;           //handle for serial port I/O

void delay_ms(clock_t millis)
{
   //  This uses a lot of cpu time to run. find out hoe to use system timer.
   clock_t endtime;
   endtime = millis + clock();
   while( endtime > clock() )         ;

}

#endif


/*
=============================================
Sec 1.0 #defines for 7SEG	
=============================================
*/


/*
   01
20   02
   40
10   04
   08

  ra
rf   rb
  rg   
re   rc
  rd
*/


/* 7 segment definitions */

#define ra 0x40
#define rb 0x20
#define rc 0x10
#define rd 0x08
#define re 0x04
#define rf 0x02
#define rg 0x01
#define rh 0x80

#define r0 0x00



#define D_0 ra+rb+rc+rd+ re+rf+r0+r0
#define D_1 rb+rc
#define D_2 ra+rb+r0+rd+ re+r0+rg+r0
#define D_3 ra+rb+rc+rd+ r0+r0+rg+r0
#define D_4 r0+rb+rc+r0+ r0+rf+rg+r0
#define D_5 ra+r0+rc+rd+ r0+rf+rg+r0
#define D_6 ra+r0+rc+rd+ re+rf+rg+r0
#define D_7 ra+rb+rc+r0+ r0+r0+r0+r0
#define D_8 ra+rb+rc+rd+ re+rf+rg+r0
#define D_9 ra+rb+rc+r0+ r0+rf+rg+r0
#define D_A ra+rb+rc+r0+ re+rf+rg+r0
#define D_B r0+r0+rc+rd+ re+rf+rg+r0
#define D_C ra+r0+r0+rd+ re+rf+r0+r0
#define D_D r0+rb+rc+rd+ re+r0+rg+r0
#define D_E ra+r0+r0+rd+ re+rf+rg+r0
#define D_F ra+r0+r0+r0+ re+rf+rg+r0

#define D_r re+rg
#define D_o r0+r0+rc+rd+ re+r0+rg+r0

#define D_OFF r0




#define NDIGITS 16


/*
=============================================
Sec 1.0 ProtoTypes
=============================================
*/


void writeBytes(int descriptor, int count);
void writeBytes2( int descriptor, void * serialBuffer,  int count );
void readBytes(int descriptor, int count);

void setModeIIC(int fd, char mode); 
void setModeIICatod(int fd, char mode); 
void setModeIICultraSound(int fd, char mode);
void setModeIICdisp(int fd, char mode, char* Text);
int  setModeIICpollDisp(int fd, char mode);



int  setModeIICcolorDuino(int fd, char mode);
int  setModeIICcolorDuinoPixel(int fd, char x, char y,char r,char g,char b);

int  aatoint(char hi,char lo);


void getModeISS_ver(int fd, char mode);
void getModeISS_ser(int fd, char mode);

void setModeISS_setIOmode(int fd, char mode); 		/* see data sheet  */
void setModeISS_setIOchangemode(int fd, char mode);     /* see data sheet  */
void setModeISS_setIO_I2C_S_20k(int fd, char mode); /* see data sheet  */

void setModeISS_setPins(int fd, char mode); 		/* see data sheet  */
int  setModeISS_getPins(int fd, char mode); 			/* see data sheet  */
int  setModeISS_getAD(int fd, char pin); 			/* see data sheet  */
void setModeISS_disp(int fd, char mode, char* Text);
int  setModeISS_pollDisp(int fd, char mode);
int  setModeISS_pollDispTimeout(int fd, char mode);



void ledRGB( int fd );

/* MAX2719 7-seg display */
void sendMAX2719( int fd , int cmd );
void sendMAX2719_segs( int fd , int cmd );
void sendMAX2719_segs_blank( int fd , int cmd );
void sendMAX2719_digits( int fd , int cmd );
void sendMAX2719_help( int fd , int cmd );
void sendMAX2719_cmds( int fd , int lists, int *cmds );  //2x2 list of cmds


void sendMAX2719xyz( int fd , int x , int y, int z );  // set LED on off


/*
=============================================
Sec 1.0 
=============================================
*/


char serialBuffer[100];					// Serial buffer sto store data for I/O

int bits[] = { 1,2,4,8,0x10,0x20,0x40,0x80 };

int cmds[][] = { 
 // 0 
 {
  0x0C01,
  0x09ff,
  0x0801,
  0x0702,
  0x0603,
  0x0504,
  0x0405,
  0x0306,
  0x0207,
  0x0108,
  -1},
 { //1
   0x0C01,
   0x09ff,
   0x0802,
   0x0705,
   0x0602,
   0x0505,
   0x0402,
   0x0305,
   0x0202,
   0x0105,
	-1},
{ //2
   0x0C01,
   0x0900,
   D_E+0x0800,
   D_r+0x0700,
   D_r+0x0600,
   D_o+0x0500,	
   D_r+0x0400,
   D_OFF+0x0300,
   D_OFF+0x0200,
   D_OFF+0x0100,
   -1
},
{ //3 
   0x0C01,
   0x0900,
   0x0800,
   0x0700,
   0x0600,
   0x0500,	
   0x0400,
   0x0300,
   0x0200,
   0x0100,
   -1
},
{ //4
   0x0C01,
   0x09ff,
   0x0800,
   0x0700,
   0x0600,
   0x0500,	
   0x0400,
   0x0300,
   0x0200,
   0x0100,
   -1
},
{ //5
   0x0C01,
   0x0900,
   0x0800+ra+rd,
   0x0700+ra+rd,
   0x0600+ra+rd,
   0x0500+ra+rd,	
   0x0400+ra+rd,
   0x0300+ra+rd,
   0x0200+ra+rd,
   0x0100+ra+rd,
   -1
},
{ //5
   0x0C01,
   0x0900,
   0x0800+rd,
   0x0700+rg,
   0x0600+ra,
   0x0500+rg,	
   0x0400+rd,
   0x0300+re+rd+rc,
   0x0200+re+rd+rc,
   0x0100+re+rd+rc,
   -1
},
{
  -1
},
{
  -1},
{
  -1}
};


/*
=============================================
Sec 1.0 
=============================================
*/

int main(int argc, char **argv)
{
	int fd;						// File descriptor of port we will talk to 
        int count;
	int x=30;
	int y=00;
	int sum=00;

	int keys=0,lastKeys=0,keyDiff = 0;

#ifdef linux
	//char *portName = "/dev/ttyAMA0";		// Name of the UART port on the Raspberry pi
	char *portName = "/dev/ttyACM0";		// Name of the UART port on the Raspberry pi
	//char   *portName = "/dev/ttyUSB0";		// Name of the IIC module

	struct termios options;				// Port options
	
	printf("\n=====================\nUSB-ISS and MAX2719 Linux version:-	\n=====================\n");
	DELAYL
	DELAYL
	
    printf(" sizeof: %d aatoInt: %d", sizeof( fd ), aatoint( '1','2' ) );

	fd = open(portName, O_RDWR | O_NOCTTY);		// Open port for read and write not making it a controlling terminal
	if (fd == -1)
	{
   		perror("openPort: Unable to open port ");		// If open() returns an error
	} else {
	  printf("\n usb iic usb open \n");
	} 

	// setModeIIC(fd, 1);						// Set the mode of the MD49 to 1
	tcgetattr(fd, &options);
	cfsetispeed(&options, B19200);						// Set baud rate
	cfsetospeed(&options, B19200);					
	cfmakeraw(&options);
	tcflush(fd, TCIFLUSH);

	// http://tldp.org/HOWTO/Serial-Programming-HOWTO/x115.html

	// printf("c_cc[VMIN]  %04X\n",options.c_cc[VMIN]);
	// printf("c_cc[VTIME] %04X\n",options.c_cc[VTIME]);
	options.c_cc[VMIN]  = 1; // wait for atleast these CHARs
	options.c_cc[VTIME] = 3; // wait deci seconds.

	tcsetattr(fd, TCSANOW, &options);
	//usleep(1000 );							// Sleep for UART to power up and set options
        DELAY
	tcflush(fd, TCIFLUSH);
	cfsetospeed(&options, B19200);					
	cfmakeraw(&options);
	tcflush(fd, TCIFLUSH);

	// http://tldp.org/HOWTO/Serial-Programming-HOWTO/x115.html
	//usleep(1000 divt);							// Sleep for UART to power up and set options
        DELAY
	// displaySoftwareValue(fd);					// Display the software version of the MD49

#endif	
#ifdef tcc
    char buff[100];
    int io_port = COM_PORT;
    clock_t timeout;

	printf("\n++++++++++\nUSB-ISS and MAX2719 TCC version:-	\n++++++++++\n");
	DELAYL
	DELAYL


    if(!rs_initialise( io_port ,19200, '8', 'N'))
    {
         printf("Opening Port Failed");
         delay_ms(5000  );
         exit(1);
    }
    rs_terminate(io_port);


    if(!rs_initialise( io_port ,19200, '8', 'N'))
    {
         printf("Opening Port Failed");
         delay_ms(5000  );
         exit(1);
    }
#endif


/*
  #include <Colorduino.h>          //colorduino library

  #define I2C_DEVICE_ADDRESS 0x05  //I2C address for this device 
  #define START_OF_DATA 0x10       //data markers
  #define END_OF_DATA 0x20         //data markers
*/



#ifdef COMMENT

/*
 while(1){
//   setModeIICcolorDuino( fd, '4' );


   setModeIICcolorDuinoPixel(fd,  1,1,255,255,255);
   DELAYL
   setModeIICcolorDuinoPixel(fd,  1,2,255,0,0);
   DELAYL
   setModeIICcolorDuinoPixel(fd,  1,3,0,255,0);
   DELAYL
   setModeIICcolorDuinoPixel(fd,  1,4,0,0,255);
   DELAYL


   DELAYL

   setModeIICcolorDuinoPixel(fd,  0,0,0,0,0);
   DELAYL
   setModeIICcolorDuinoPixel(fd,  3,1,0,0,0);
   DELAYL
   setModeIICcolorDuinoPixel(fd,  3,3,0,0,0);
   DELAYL
   setModeIICcolorDuinoPixel(fd,  4,4,0,0,0);
   DELAYL
   setModeIICcolorDuinoPixel(fd,  0,0,0,0,0);

   DELAYL
   setModeIICcolorDuinoPixel(fd,  1,1,0,0,0);
   DELAYL
   setModeIICcolorDuinoPixel(fd,  1,2,0,0,0);
   DELAYL
   setModeIICcolorDuinoPixel(fd,  1,3,0,0,0);
   DELAYL
   setModeIICcolorDuinoPixel(fd,  1,4,0,0,0);
   DELAYL
   setModeIICcolorDuinoPixel(fd,  1,5,0,0,0);

   DELAYL
   setModeIICcolorDuinoPixel(fd,  5,5,255,128,0);
   DELAYL
   setModeIICcolorDuinoPixel(fd,  5,6,255,64,0);
   DELAYL
   setModeIICcolorDuinoPixel(fd,  6,5,255,32,0);


   x=x+y/4;
   y=y-x/4;
   DELAYL
   printf(" x,y = %d,%d\n",x,y);
   setModeIICcolorDuinoPixel(fd,  x/8+4,y/9+4,(255+sum)%256,(32+sum<<1)%256,(0+sum<<2)%256 );
   sum++;   

 }
*/
#endif


printf("=== setModeISS_ver ===================\n");
    getModeISS_ver( fd, 0);
    DELAYL

    getModeISS_ser( fd, 0);
    sleep(1000);
    DELAYL

printf("======================\n");
    setModeISS_setIO_I2C_S_20k(fd, 2 );
    DELAYL

    setModeISS_setIO_I2C_S_20k(fd, 2 );
    DELAYL

    setModeISS_disp( fd, 0x0c," press 1 or 3       ");

    /* the poll below trys to read more characters than requested.
    This syncronizes future polls */	

    keys = setModeISS_pollDispTimeout(fd, ' ');

 while(1){
	printf("here\n");
	keys = setModeISS_pollDisp(fd, ' ');
	keyDiff = ( keys & ~lastKeys );

	printf("keys: %02x %02x %02x\n", keys , lastKeys,( (keys & ~lastKeys ) & 0xff )  );
        if ( ( keyDiff & 0x01 ) > 0){
			/*        12345678901234567890 */
          setModeISS_disp( fd, 0x0c,"  ++  hello    ++   ");
          setModeISS_disp( fd, 0x00,"  +    doug     +   ");
          setModeISS_disp( fd, 0x00,"- +     & &     + - ");
          setModeISS_disp( fd, 0x04,"  ++   Alice   ++   ");
        } 


	if ( (  keyDiff & 0x02 ) > 0){
			/*        12345678901234567890 */
          setModeISS_disp( fd, 0x0c,"                    ");
          setModeISS_disp( fd, 0x00,"      2  pressed    ");
          setModeISS_disp( fd, 0x00,"                    ");
          setModeISS_disp( fd, 0x06,"                    ");
	}     

	if ( (  keyDiff & 0x04 ) > 0){
			/*        12345678901234567890 */
          setModeISS_disp( fd, 0x0c," + * + * + * + * * *");
          setModeISS_disp( fd, 0x00,"* * * * * * * * * * ");
          setModeISS_disp( fd, 0x00," * + * + * + * * * *");
          setModeISS_disp( fd, 0x04,"* * * * * * * * * * ");
	}     

	if ( (  keyDiff & 0x08 ) > 0){
			/*           12345678901234567890 */
          setModeISS_disp( fd, 0x0c,"                    ");
          setModeISS_disp( fd, 0x00," #----------------# ");
          setModeISS_disp( fd, 0x00,"                    ");
          setModeISS_disp( fd, 0x05,"                    ");
	}     




	lastKeys = keys;
    DELAY
	sleep(100);
}



          
 setModeIICdisp( fd, 0x0c," press 1 or 3       ");

 while(1){

	keys = setModeIICpollDisp(fd, ' ');

	keys = setModeIICpollDisp(fd, ' ');

	printf("keys: %02x %02x %02x\n", keys , lastKeys,( (keys & ~lastKeys ) & 0xff )  );
        if ( ( ( keys & ~lastKeys ) & 0x01 ) > 0){
			/*        12345678901234567890 */
          setModeIICdisp( fd, 0x0c,"      hello         ");
          setModeIICdisp( fd, 0x00,"       doug         ");
          setModeIICdisp( fd, 0x00,"+ - + - + - + - + - ");
          setModeIICdisp( fd, 0x00,"       Alice        ");
        } 
	if ( ( ( keys & ~lastKeys ) & 0x04 ) > 0){
			/*        12345678901234567890 */
          setModeIICdisp( fd, 0x0c," * * * * * * * * * *");
          setModeIICdisp( fd, 0x00,"* * * * * * * * * * ");
          setModeIICdisp( fd, 0x00," * * * * * * * * * *");
          setModeIICdisp( fd, 0x00,"* * * * * * * * * * ");
	}     
	lastKeys = keys;
        DELAY
}

	return 1 ;

	printf("\n ==================== \n");

	getModeISS_ver(fd, 1);
    	DELAYL
	getModeISS_ser(fd, 1);
    	DELAYL
	printf("\n ==================== \n");
	setModeISS_setIOmode(       fd, 0x00 );
	DELAY
	setModeISS_setIOchangemode( fd, 0x00 );
	DELAY
	
	while(1){

/*
          sendMAX2719xyz( int fd , int x , int y, int z );
*/

	  printf(" sendMAX2719xyz( fd , 1,1, 1 ); \n");

	  sendMAX2719( fd , 0x0C01 ); // ShutDown 0c01 is normal operation
	  sendMAX2719( fd , 0x0B07 ); // Number of digits
	  sendMAX2719( fd , 0x0F00 ); // LAMP TEST off
	  sendMAX2719( fd , 0x0900 ); // MODE  
	  sendMAX2719( fd , 0x02AA ); // intensity  


	  sendMAX2719( fd , 0x0100 ); // digit 0
	  sendMAX2719( fd , 0x0200 ); // digit 0
	  sendMAX2719( fd , 0x0300 ); // digit 0
	  sendMAX2719( fd , 0x0400 ); // digit 0

	  sendMAX2719( fd , 0x0500 ); // digit 0
	  sendMAX2719( fd , 0x0600 ); // digit 0
	  sendMAX2719( fd , 0x0700 ); // digit 0
	  sendMAX2719( fd , 0x0800 ); // digit 0



          sendMAX2719xyz( fd , 0,0, 1 );
	  DELAYL
          sendMAX2719xyz( fd , 0,1, 1 );
	  DELAYL
          sendMAX2719xyz( fd , 0,2, 1 );
	  DELAYL
          sendMAX2719xyz( fd , 0,3, 1 );
	  DELAYL
          sendMAX2719xyz( fd , 0,4, 1 );
	  DELAYL
          sendMAX2719xyz( fd , 0,5, 1 );
	  DELAYL
          sendMAX2719xyz( fd , 0,6, 1 );
	  DELAYL
          sendMAX2719xyz( fd , 0,7, 1 );
	  DELAYL

          for( count = 0 ; count < 8 ;  count++ ){
            sendMAX2719xyz( fd , 0,count, 1 );
  	    DELAYL
          }
          for( count = 0 ; count < 8 ;  count++ ){
            sendMAX2719xyz( fd , 7,count, 1 );
  	    DELAYL
          }

          for( count = 0 ; count < 8 ;  count++ ){
            sendMAX2719xyz( fd , count,count, 1 );
  	    DELAYL
          }
          for( count = 0 ; count < 8 ;  count++ ){
            sendMAX2719xyz( fd , 7-count ,count, 1 );
  	    DELAYL
          }
          for( count = 0 ; count < 8 ;  count++ ){
            sendMAX2719xyz( fd , count,0, 1 );
  	    DELAYL
          }
          for( count = 0 ; count < 8 ;  count++ ){
            sendMAX2719xyz( fd , count,7, 1 );
  	    DELAYL
          }


/*
}
	while(1){
*/

	  sendMAX2719( fd , 0x09FF ); // MODE  

  
	  //	ledRGB( fd );
	  //sendMAX2719( fd , 0xAA );
	  sendMAX2719_help( fd , 0x00 );
	  sendMAX2719_segs_blank( fd , 0x00 );
	  sendMAX2719_cmds( fd , 0, cmds[0] );
	  sendMAX2719_help( fd , 0x00 );
	  sendMAX2719_help( fd , 0x0f01 );
	  sendMAX2719_cmds( fd , 1, cmds[1] );
	  sendMAX2719_cmds( fd , 3, cmds[3] );
	  sendMAX2719_cmds( fd , 2, cmds[2] );
	  sendMAX2719_cmds( fd , 3, cmds[3] );
	  sendMAX2719_cmds( fd , 4, cmds[4] );
	  sendMAX2719_cmds( fd , 3, cmds[3] );
	  sendMAX2719_cmds( fd , 5, cmds[5] );
	  sendMAX2719_cmds( fd , 3, cmds[3] );
	  sendMAX2719_cmds( fd , 6, cmds[6] );
	  sendMAX2719_cmds( fd , 3, cmds[3] );
	  sendMAX2719_cmds( fd , 7, cmds[7] );
	  sendMAX2719_cmds( fd , 3, cmds[3] );

  	  setModeISS_setIOmode( 	  fd, 0x00 );
	  setModeISS_setIOchangemode( fd, 0x00 );



	  sendMAX2719( fd , 0x0C01 ); // ShutDown 0c01 is normal operation
	  sendMAX2719( fd , 0x0B07 ); // Number of digits
	  sendMAX2719( fd , 0x0F00 ); // LAMP TEST off
	  sendMAX2719( fd , 0x09AA ); // MODE  
	  sendMAX2719( fd , 0x02AA ); // intensity  
	  
	  sendMAX2719( fd , 0x0A01 ); // intensity  
	  sendMAX2719( fd , 0x0A03 ); // intensity
	  sendMAX2719( fd , 0x0A05 ); // intensity
	  sendMAX2719( fd , 0x0A01 ); // intensity
	  sendMAX2719( fd , 0x0F00 ); // lamp test on  
	  sendMAX2719( fd , 0x0F00 ); // lamp test off
//	  sendMAX2719( fd , 0x0C00 ); // ShutDown 0c00 is shut down
	  sendMAX2719( fd , 0x0C01 ); // ShutDown 0c01 is normal operation

  	  setModeISS_setIOmode(   	  fd, 0x00 );
	  setModeISS_setIOchangemode( fd, 0x00 );
	  
	/* init blank */  
          sendMAX2719_segs_blank(     fd, 0x00 );
	  sleep(1);
          sendMAX2719_help( fd , 0x00 );
          sendMAX2719( fd , 0x0100 ); // digit
          sendMAX2719( fd , 0x0207 ); // digit
	  sleep(4);
	/* HELP */
	/*
	  sendMAX2719( fd , 0x0B07 ); // Number of digits
	  sendMAX2719( fd , 0x09ff ); // decode mode
	  sendMAX2719( fd , 0x080C ); // digit H
      sendMAX2719( fd , 0x070B ); // digit E
	  sendMAX2719( fd , 0x060D ); // digit L
      sendMAX2719( fd , 0x050E ); // digit P

	  sendMAX2719( fd , 0x040F ); // digit  
	  sendMAX2719( fd , 0x030A ); // digit -
	  sendMAX2719( fd , 0x0208 ); // digit 8
	  sendMAX2719( fd , 0x0100 ); // digit 0
*/
	/* init blank */  
      sendMAX2719_segs_blank(     fd, 0x00 );
      sleep(2);
	  
	  
	/* 7-Segments */    
	  sendMAX2719( fd , 0x0101 ); // digit 1
	  sendMAX2719( fd , 0x0202 ); // digit 2
	  sendMAX2719( fd , 0x0304 ); // digit 3
	  sendMAX2719( fd , 0x0408 ); // digit 4
	  sendMAX2719( fd , 0x0510 ); // digit 5
	  sendMAX2719( fd , 0x0620 ); // digit 6
	  sendMAX2719( fd , 0x0740 ); // digit 7
	  sendMAX2719( fd , 0x0880 ); // digit 8
	  

      sleep(2);
	   
	  


	  sendMAX2719( fd , 0x0B07 ); // Number of digits
	  sendMAX2719( fd , 0x0B06 ); // Number of digits
	  sendMAX2719( fd , 0x0B05 ); // Number of digits
	  sendMAX2719( fd , 0x0B04 ); // Number of digits
	  sendMAX2719( fd , 0x0B03 ); // Number of digits
	  sendMAX2719( fd , 0x0B07 ); // Number of digits
	  
	  sendMAX2719( fd , 0x0101 ); // digit 1
	  sendMAX2719( fd , 0x0202 ); // digit 2
	  sendMAX2719( fd , 0x0304 ); // digit 3
	  sendMAX2719( fd , 0x0408 ); // digit 4
	  sendMAX2719( fd , 0x0510 ); // digit 5
	  sendMAX2719( fd , 0x0620 ); // digit 6
	  sendMAX2719( fd , 0x0740 ); // digit 7
	  sendMAX2719( fd , 0x0880 ); // digit 8
	  
	  sendMAX2719( fd , 0x0F00 ); // lamp test off 0xf00

	  sendMAX2719( fd , 0x0900 ); // decode mode

	  sendMAX2719( fd , 0x0100 ); // digit 1
	  sendMAX2719( fd , 0x0200 ); // digit 2
	  sendMAX2719( fd , 0x0300 ); // digit 3
	  sendMAX2719( fd , 0x0400 ); // digit 4
	  sendMAX2719( fd , 0x0500 ); // digit 5
	  sendMAX2719( fd , 0x0600 ); // digit 6
	  sendMAX2719( fd , 0x0700 ); // digit 7
	  sendMAX2719( fd , 0x0800 ); // digit 8
	  
	  sendMAX2719( fd , 0x0101 ); // digit 1
	  sendMAX2719( fd , 0x0202 ); // digit 2
	  sendMAX2719( fd , 0x0304 ); // digit 3
	  sendMAX2719( fd , 0x0408 ); // digit 4
	  sendMAX2719( fd , 0x0510 ); // digit 5
	  sendMAX2719( fd , 0x0620 ); // digit 6
	  sendMAX2719( fd , 0x0740 ); // digit 7
	  sendMAX2719( fd , 0x0880 ); // digit 8
	  
	  sendMAX2719( fd , 0x0F00 ); // lamp test off
	}
	printf("\n ==================== \n");

	close(fd);							// Close port
	
	return 0;
}

/*
=============================================
Sec 1.0 
=============================================
*/


#ifdef tcc


HANDLE rs_initialise (int io_port, const long int BaudRate, const char parity, const char data)
{
    BOOL bPortReady;
    DCB dcb;
	COMMTIMEOUTS CommTimeouts;

    char ComPortName[5]="COM ";
    ComPortName[3]='0'+ io_port;
    hCom = CreateFile(ComPortName, GENERIC_READ | GENERIC_WRITE,
                                  0,            // exclusive access
                                  NULL,         // no security
                                  OPEN_EXISTING,
                                  0,            // no overlapped I/O
                                  NULL);        // null template

    if ((int)hCom <= 0)
    {
        printf("serial port COM%d connect fail %s error %d\n\r", io_port, ComPortName, GetLastError());
        return 0;
    }
    //else                printf(" serial port COM%d connect OK \n\r", io_port);

    bPortReady = SetupComm(hCom, 128, 128); // set buffer sizes
    if (!bPortReady )
    {
        printf("serial port COM%d SetupComm fail  %d\n\r", io_port,  GetLastError());
        return 0;
    }
    //else                printf(" serial port COM%d connect OK \n\r", io_port);

    bPortReady = GetCommState(hCom, &dcb);
    if (!bPortReady )
    {
        printf("serial port COM%d  GetCommState fail  %d\n\r", io_port,  GetLastError());
        return 0;
    }
    //  else                printf(" serial port COM%d connect OK \n\r", io_port);
    dcb.BaudRate = BaudRate;
    if( data == '7') dcb.ByteSize = 7;
    else             dcb.ByteSize = 8;
    if( parity == 'E') dcb.Parity = EVENPARITY;
    if( parity == 'O') dcb.Parity = ODDPARITY;
    else               dcb.Parity = NOPARITY;
    dcb.StopBits = ONESTOPBIT;
    dcb.fAbortOnError = TRUE;

    // set XON/XOFF
    dcb.fOutX = FALSE;                       // XON/XOFF off for transmit
    dcb.fInX = FALSE;                        // XON/XOFF off for receive
    // set RTSCTS
    dcb.fOutxCtsFlow = FALSE;               // turn off CTS flow control
    dcb.fRtsControl = FALSE;                // RTS_CONTROL_HANDSHAKE; //
    // set DSRDTR
    dcb.fOutxDsrFlow = FALSE;               // turn off DSR flow control
    //dcb.fDtrControl = DTR_CONTROL_ENABLE; // DTR handshake
    dcb.fDtrControl = DTR_CONTROL_DISABLE;  //
    // dcb.fDtrControl = DTR_CONTROL_HANDSHAKE; //

    bPortReady = SetCommState(hCom, &dcb);
    if (!bPortReady )
    {
        printf("serial port COM%d  SetCommState fail  %d\n\r", io_port,  GetLastError());
        return 0;
    }

    // Communication timeouts
    //COMMTIMEOUTS CommTimeouts;
    bPortReady = GetCommTimeouts (hCom, &CommTimeouts);
    CommTimeouts.ReadIntervalTimeout = 500 ;
    CommTimeouts.ReadTotalTimeoutConstant = 500 ;
    CommTimeouts.ReadTotalTimeoutMultiplier = 1 ;
    CommTimeouts.WriteTotalTimeoutConstant = 5 ;
    CommTimeouts.WriteTotalTimeoutMultiplier = 1 ;
    bPortReady = SetCommTimeouts (hCom, &CommTimeouts);
    if (!bPortReady )
    {
        printf("serial port COM%d SetCommTimeouts fail  %d\n\r", io_port,  GetLastError());
        return 0;
    }
    else
    {
        printf(" serial port COM%d connect OK \n\r", io_port);
    }
    return (hCom);
}

void rs_terminate(const int io_port)
{
   CloseHandle(hCom);
}

#endif


void writeBytes(int descriptor, int count) {
#ifdef linux
   int cnt;
	if (( cnt = write(descriptor, serialBuffer, count)) == -1) {	// Send data out	
		perror("Error writing");
		close(descriptor);					// Close port if there is an error
		exit(1);
	}
#endif

#ifdef tcc
    BOOL bWriteRC;
    static DWORD iBytesWritten;
    bWriteRC = WriteFile(hCom, serialBuffer, count, &iBytesWritten,NULL);

    printf( " iBytesWritten: %d \n",(int)iBytesWritten);

    return;
#endif
}



void writeBytes2( int descriptor, void * serialBuffer,  int count ) {
#ifdef linux
   int cnt;
	if (( cnt = write(descriptor, serialBuffer, count)) == -1) {	// Send data out	
		perror("Error writing");
		close(descriptor);					// Close port if there is an error
		exit(1);
	}
#endif

#ifdef tcc
    BOOL bWriteRC;
    static DWORD iBytesWritten;
    bWriteRC = WriteFile(hCom, serialBuffer, count, &iBytesWritten,NULL);
    return;
#endif
}



void readBytes(int descriptor, int count) {

#ifdef linux

	int count_rd;
	if ( ( count_rd = read(descriptor, serialBuffer, count) ) == -1) {		// Read back data into buf[]
		perror("Error reading ");
		close(descriptor);					// Close port if there is an error
		exit(1);
	}
	// printf(" count: %d %d ", count_rd ,  count );

#endif

#ifdef tcc
    char rxchar;
    BOOL bReadRC;
    static DWORD iBytesRead;
    bReadRC = ReadFile(hCom, serialBuffer, count, &iBytesRead, NULL);

#endif

}


/*
=============================================
Sec 1.0 
=============================================
*/

void setModeIIC(int fd, char mode) {
	//
	serialBuffer[0] = 0x5A;		
	serialBuffer[1] = 0x10;						// Mode we wish to set
	serialBuffer[2] = mode ;					// Mode we wish to set
	serialBuffer[3] = 0x00;						// Mode we wish to set
	writeBytes(fd, 4);

	readBytes( fd,1);
	printf("%02X \n", serialBuffer[0] );
        
}


void setModeIICatod(int fd, char mode) {

	setModeIIC( fd, 0x0C );

	
	//usleep(100000 divt );						// Sleep for UART to power up and set options
	DELAY
	serialBuffer[0] = 0x5A;		
	serialBuffer[1] = 0x12;						// Mode we wish to set
	serialBuffer[2] = 0x00;						// Mode we wish to set
	serialBuffer[3] = 0x00;						// Mode we wish to set

	writeBytes(fd, 4);
        //usleep(  600000   divt );
        DELAYL
	readBytes( fd,8);
	printf(  "%02X %02X   %02X %02X \n", serialBuffer[0] , serialBuffer[1],        serialBuffer[2], serialBuffer[3] );
}

void setModeIICultraSound(int fd, char mode) {

/* 82	0x52	 Real Ranging Mode - Result in micro-seconds */
	
/*
 The SRF02 appears as a set of 6 registers.

Location	Read			Write	
0		Software Revision	Command Register
1		Unused (reads 0x80)	N/A 
2		Range High Byte		N/A
3		Range Low Byte		N/A
4	 Autotune Minimum - High Byte	 N/A
5	 Autotune Minimum - Low Byte	 N/A

*/

/*
Writing to I2C devices with a 1 byte internal address register
This includes almost all I2C devices. Following the I2C_AD1 command you send the device I2C address, 
then the devices internal register address you want to write to and the number of bytes you're writing. 
The maximum number of data bytes should not exceed 64 so as not to overflow the USB-I2C's internal buffer.

 	Primary USB-I2C command	Device Address + R/W bit	Device internal register	Number of data bytes	The data bytes
Byte Type	I2C_AD1	Addr+R/W	Reg	Byte Count	Data
Example	0x55	0xE0	0x00	0x01	0x51
Meaning	Primary USB-I2C command	SRF08 I2C address	SRF08 command Reg	One command byte follows	Start ranging in cm
This 5 byte sequence starts an SRF08 at address 0xE0 ranging. 

All 5 bytes should be sent to the USB-I2C in one sequence. 
A gap will result in the USB-I2C re-starting its internal command synchronization loop and ignoring the message. 
After all bytes have been received the USB-I2C performs the IC2 write operation out to the SRF08 
and sends a single byte back to the PC. 

This returned byte will be 0x00 (zero) if the write command failed and non-zero if the write succeeded. 
The PC should wait for this byte to be returned (timing out after 500mS) before proceeding with the next transaction.

*/
	
/*	I2C_AD1	0x55	 Read/Write single or multiple bytes for 1 byte addressed devices (the majority of devices will use this one) */
	
	int aai, aaat ;
	
	
	serialBuffer[0] = 0x55;	// iic command to do iic 	
	serialBuffer[1] = 0xE0;	// iic address
	serialBuffer[2] = 0x00;	// device internal reg
	serialBuffer[3] = 0x01;	// number of bytes to write
	serialBuffer[4] = 0x51;	// 0x52	 Real Ranging Mode - Result in micro-seconds

	writeBytes(fd, 5);
	readBytes( fd,1);
	/*
	if ( serialBuffer[0] == 0 ) {
	  printf(  "not ok: %02X ", serialBuffer[0] );
	}
        */
        //usleep(  100000  divt  );
	DELAYL
	// Set up the iic for a read operation.
	serialBuffer[0] = 0x55;	// iic command to do iic 	
	serialBuffer[1] = 0xE1;	// iic address
	serialBuffer[2] = 0x00;	// device internal reg
	serialBuffer[3] = 0x06;	// number of bytes to read
	writeBytes(fd, 4);
	readBytes( fd,6);

 	// au.b1[0] = serialBuffer[3];
 	// au.b1[1] = serialBuffer[2];

        aai  = aatoint( serialBuffer[3], serialBuffer[2]);
        aaat = aatoint( serialBuffer[5], serialBuffer[4]);

//	printf(  "ver: %02X %02X range: %04X cm  %06d cm ", serialBuffer[0], serialBuffer[1], aai,aai  );   // serialBuffer[2], serialBuffer[3] 
//	printf(  "AT:  %04X cm  %06d cm \n", aaat, aaat );

//	printf(  "srf08:range  %06d cm, autoTune: %06d \n",  aai,aaat  ); 
//	printf(  "srf08: %06d cm,  %06d cm \n",  aaat,aai  ); 

	printf(  "srf08: %06d cm,  %06d cm %0*d+\n",  aaat,aai,(int)(aai/4),1  ); 

}

void setModeIICdisp(int fd, char mode, char* Text) {

	serialBuffer[0] = 0x55;	// iic command to do iic 	
	serialBuffer[1] = 0xC6;	// iic address
	serialBuffer[2] = 0x00;	// device internal reg
	serialBuffer[3] = strlen(Text)+1;	// number of bytes to write
	serialBuffer[4] = mode;	// 0x52	 Real Ranging Mode - Result in micro-seconds
	writeBytes(fd, 5);
	writeBytes2(fd, ( void * ) Text, strlen(Text) );
	readBytes( fd,1);
	/*
	if ( serialBuffer[0] == 0 ) {
	  printf(  "not ok: %02X ", serialBuffer[0] );
	}
        */
}
/*
Reading multiple bytes from I2C devices without setting a new address
 This is used for devices that do not have an internal register address but returns multiple bytes. Examples of such devices are the Honeywell ASDX DO series pressure sensors. This command  can also be used for devices that do have an internal address which it increments automatically between reads and doesn't need to be set each time, such as eeproms. In this case you would use command I2C_AD1 or I2C_AD2 for the first read, then I2C_MUL for subsequent reads. Here is an example of reading the two byte pressure from the Honeywell sensor.

I2C_MUL ASDX I2C address + Read bit Number of bytes to read 
0x54 0xF1 0x02 


*/
int setModeIICpollDisp(int fd, char mode) {

	serialBuffer[0] = 0x54;	// iic command to do iic 	
	serialBuffer[1] = 0xC7;	// iic address
	serialBuffer[2] = 0x04;	// number of bytes to read
	writeBytes(fd, 3 );

        DELAYL
	readBytes( fd, 4 );
	printf(  "setModeIICpollDisp: %02X %02X   %02X %02X \n", serialBuffer[0] , serialBuffer[1],        serialBuffer[2], serialBuffer[3] );
	
	return ( (0+ (int) serialBuffer[1]) & 0xff ) ;
}

/*
 #include <Colorduino.h>          //colorduino library

 #define I2C_DEVICE_ADDRESS 0x05  //I2C address for this device 
 #define START_OF_DATA 0x10       //data markers
 #define END_OF_DATA 0x20         //data markers

*/

int  setModeIICcolorDuino(int fd, char mode){

  int pp;
	serialBuffer[0] = 0x55;	// iic command to do iic 	
	serialBuffer[1] = 0x0A;	// iic address
	serialBuffer[2] = 0x10;	// device internal reg
	serialBuffer[3] = 35;	// number of bytes to write
	serialBuffer[4] = 5;	// color plane /* colour, R,G,B, top R,G,B, bottom R G B 

        pp=5;	
	/* row 1 */
	serialBuffer[pp++] = 0xFF;	// 
	serialBuffer[pp++] = 0xff;	// 
	serialBuffer[pp++] = 0xff;	// 
	serialBuffer[pp++] = 0xff;	// 

	serialBuffer[pp++] = 0xff;	// 
	serialBuffer[pp++] = 0x7F;	// 
	serialBuffer[pp++] = 0xff;	// 
	serialBuffer[pp++] = 0x7F;	// 

	/* row 2 */
	serialBuffer[pp++] = 0x7F;	// 
	serialBuffer[pp++] = 0xff;	// 
	serialBuffer[pp++] = 0x7F;	// 
	serialBuffer[pp++] = 0xff;	// 

	serialBuffer[pp++] = 0x7F;	// 
	serialBuffer[pp++] = 0x7F;	// 
	serialBuffer[pp++] = 0x7F;	// 
	serialBuffer[pp++] = 0x7F;	// 

	/* row 3 */
	serialBuffer[pp++] = 0x7F;	// 
	serialBuffer[pp++] = 0x7F;	// 
	serialBuffer[pp++] = 0x7F;	// 
	serialBuffer[pp++] = 0x7F;	// 

	serialBuffer[pp++] = 0x7F;	// 
	serialBuffer[pp++] = 0x7F;	// 
	serialBuffer[pp++] = 0x7F;	// 
	serialBuffer[pp++] = 0x7F;	// 

	/* row 4 */
	serialBuffer[pp++] = 0x7F;	// 
	serialBuffer[pp++] = 0x7f;	// 
	serialBuffer[pp++] = 0x7f;	// 
	serialBuffer[pp++] = 0x7f;	// 

	serialBuffer[pp++] = 0x7f;	// 
	serialBuffer[pp++] = 0x7f;	// 
	serialBuffer[pp++] = 0x7f;	// 
	serialBuffer[pp++] = 0xff;	// 

	serialBuffer[pp++] = 0x20;	// 
        pp--;
	serialBuffer[3] = pp-4;	// number of bytes to write

	writeBytes(fd, pp );
	readBytes( fd,1);

	printf( " pp: %d %d,  %d \n",  pp,  serialBuffer[3],  serialBuffer[37]);

        DELAYL
/*
	readBytes( fd, 4 );
	printf(  "setModeIICpollDisp: %02X %02X   %02X %02X \n", serialBuffer[0] , serialBuffer[1],        serialBuffer[2], serialBuffer[3] );
	return ( (0+ (int) serialBuffer[1]) & 0xff ) ;

*/

	return 0;
}

int  setModeIICcolorDuinoPixel(int fd, char x, char y,char r,char g,char b){

  int pp,ack;

        pp=0;	

	serialBuffer[pp++] = 0x55;	// iic command to do iic 	
	serialBuffer[pp++] = 0x0A;	// iic address
	serialBuffer[pp++] = 0x10;	// device internal reg
	serialBuffer[pp++] = 35;	// number of bytes to write


//	serialBuffer[pp++] = 0x20;	// 
//	serialBuffer[pp++] = 0x10;	// 

        // 4 , color  
	serialBuffer[pp++] = 0;	// 

	/* row 1 */
	serialBuffer[pp++] = x;	// 
	serialBuffer[pp++] = y;	// 

	serialBuffer[pp++] = r;	// 
	serialBuffer[pp++] = g;	// 
	serialBuffer[pp++] = b;	// 

	serialBuffer[pp++] = 0x20;	// device internal reg
	serialBuffer[3] = pp-4;	// number of bytes to write

	writeBytes(fd, pp );
	ack = readBytes( fd,1);

	printf( " pp: %d %d,  %d ack:%d\n",  pp,  serialBuffer[3],  serialBuffer[37],ack);

//        DELAYL
/*
	readBytes( fd, 4 );
	printf(  "setModeIICpollDisp: %02X %02X   %02X %02X \n", serialBuffer[0] , serialBuffer[1],        serialBuffer[2], serialBuffer[3] );
	return ( (0+ (int) serialBuffer[1]) & 0xff ) ;

*/

	return 0;
}


int aatoint(char hi,char lo){

  union ua{
    int i;
    char a[2];  // lo-hi
  } u;
  
  if ( sizeof( u.i ) == 4 ) {
    u.a[0]=hi;
    u.a[1]=lo;
    u.a[2]=0;
    u.a[3]=0;
  } else {
    printf( "sizeof( int ) != 4 - needs little enden numbers\n" );
    exit(1);
  }
  return u.i; 
}


/*
=============================================
Sec 1.0 
=============================================
*/


void getModeISS_ver(int fd, char mode) {
	//
	serialBuffer[0] = 0x5A;		
	serialBuffer[1] = 0x01;						// Mode we wish to set
	writeBytes(fd, 2);

	readBytes( fd,3);
	printf("ISS:5A-01:ID(7): %02X ver(2):%02X current mode:0x%02X \n", serialBuffer[0],serialBuffer[1],serialBuffer[2] );
        
}

void getModeISS_ser(int fd, char mode) {
	//
	serialBuffer[0] = 0x5A;		
	serialBuffer[1] = 0x03;						// Mode we wish to set
	writeBytes(fd, 2);

	readBytes( fd,7);
	
	printf("ISS:5A-03:ser: %02X %02X %02X %02X %02X %02X %02X\n", 
	serialBuffer[0],serialBuffer[1],serialBuffer[2],
	serialBuffer[3],serialBuffer[4],serialBuffer[5],
	serialBuffer[6] );

	
	printf("ISS:5A-03:ser: %c%c%c%c%c%c%c\n", 
	(char)serialBuffer[0],serialBuffer[1],serialBuffer[2],
	serialBuffer[3],serialBuffer[4],serialBuffer[5],
	serialBuffer[6] );
        
}



void setModeISS_setIOmode(int fd, char mode) {
	//
	serialBuffer[0] = 0x5A;		
	serialBuffer[1] = 0x02;						// Mode we wish to set
	serialBuffer[2] = 0x00;						// Mode we wish to set
	serialBuffer[3] = mode ;						// Mode we wish to set
	writeBytes(fd, 4);

	// does not return 
	readBytes( fd,2);
	printf("ISS:5A-02-00:IO-mode: %02X %02X \n", serialBuffer[0], serialBuffer[1] );
        
}


void setModeISS_setIOchangemode(int fd, char mode) {
	//
	serialBuffer[0] = 0x5A;		
	serialBuffer[1] = 0x02;			// Mode we wish to set
	serialBuffer[2] = 0x10;			// Mode we wish to set
	serialBuffer[3] = mode ;		// Mode we wish to set
	writeBytes(fd, 4);

	// does not return 
	readBytes( fd,2);
	printf("ISS:5A-02-00:IO-mode: %02X %02X \n", serialBuffer[0], serialBuffer[1] );
        
}

void setModeISS_setIO_I2C_S_20k(int fd, char mode) {
	//
	serialBuffer[0] = 0x5A;		
	serialBuffer[1] = 0x02;			// Mode we wish to set
	serialBuffer[2] = 0x60;			// Mode we wish to set
	serialBuffer[3] = 0x04 ;		// Mode we wish to set
	writeBytes(fd, 4);

	// does not return 
	readBytes( fd,2);
	printf("ISS:5A-02-00:IO-mode: %02X %02X \n", serialBuffer[0], serialBuffer[1] );
        
}

void setModeISS_setPins(int fd, char mode); /* see data sheet  */
int setModeISS_getPins( int fd, char mode); /* see data sheet  */
int setModeISS_getAD(   int fd, char pin); /* see data sheet  */

void setModeISS_setPins(int fd, char mode) {
	//
	serialBuffer[0] = 0x63;		
	serialBuffer[1] = mode;						// Mode we wish to set
	writeBytes(fd, 2);

	// does not return 
	readBytes( fd,1);
	//printf("ISS:5A-02-00:IO-setPins: %02X, %02X %02X \n", mode, serialBuffer[0], serialBuffer[1] );
        
}

void setModeISS_disp(int fd, char mode, char* Text) {

	/* for ISS module, only one write allowed so copy text into buffer */
        strncpy(&serialBuffer[5],Text,strlen(Text));


	serialBuffer[0] = 0x55;	// iic command to do iic 	
	serialBuffer[1] = 0xC6;	// iic address
	serialBuffer[2] = mode;	// device internal reg
	serialBuffer[3] = strlen(Text)+1;	// number of bytes to write
	serialBuffer[4] = mode;	
	writeBytes(fd, 5 + strlen(Text) ); /* must be one write */

	//writeBytes2(fd, ( void * ) Text, strlen(Text) );
	readBytes( fd,1);
	/*
	if ( serialBuffer[0] == 0 ) {
	  printf(  "not ok: %02X ", serialBuffer[0] );
	}
        */
}




int setModeISS_pollDisp(int fd, char mode) {

/*
Display control commands
The LCD03 has four registers, three of which are read only information registers. 
Register 0 is a dual purpose register, when written, it is the command register where all of the instructions from the commands section should be sent. 
When read it returns the number of free bytes in the FIFO buffer. 

====================================================================
register	Read 	Write 	
====================================================================
0	Number of free bytes in FIFO buffer	Command register	
1	Keypad state Low byte	x
2	Keypad state High byte	x
3	Version			x
====================================================================
 
*/


/*
problem - I need to timeout the read, otherwise it does not start from address 0

*/

	int * p;

	serialBuffer[0] = 0x55;	// iic command to do iic 	
	serialBuffer[1] = 0xC7;	// iic address
	serialBuffer[2] = 0;	// device internal reg - ??? - I tried 0 but it gets 3
	serialBuffer[3] = 4;	// number of bytes to read from display

	writeBytes(fd, 4 );
	readBytes( fd, 4 );	/* read 5 bytes and time out to sync otherwise read rolls around and not from 1st byte  */

	printf(  "setModeISS_pollDisp: %02X %02X   %02X %02X \n", serialBuffer[0] , serialBuffer[1],        serialBuffer[2], serialBuffer[3] );
	
        p = ( int * ) ( & serialBuffer[ 1 ] );

	return ( ( 0 + p[ 0 ] ) & 0xff ) ;
}




int setModeISS_pollDispTimeout(int fd, char mode) {

/*
Display control commands
The LCD03 has four registers, three of which are read only information registers. 
Register 0 is a dual purpose register, when written, it is the command register where all of the instructions from the commands section should be sent. 
When read it returns the number of free bytes in the FIFO buffer. 

====================================================================
register	Read 	Write 	
====================================================================
0	Number of free bytes in FIFO buffer	Command register	
1	Keypad state Low byte	x
2	Keypad state High byte	x
3	Version			x
====================================================================
 
*/


/*
problem - I need to timeout the read, otherwise it does not start from address 0

*/

	int * p;

	serialBuffer[0] = 0x55;	// iic command to do iic 	
	serialBuffer[1] = 0xC7;	// iic address
	serialBuffer[2] = 0;	// device internal reg - ??? - I tried 0 but it gets 3
	serialBuffer[3] = 4;	// number of bytes to read from display

	writeBytes(fd, 4 );
	readBytes( fd, 5 );	/* read 5 bytes and time out to sync otherwise read rolls around and not from 1st byte  */

	printf(  "setModeISS_pollDisp: %02X %02X   %02X %02X \n", serialBuffer[0] , serialBuffer[1],        serialBuffer[2], serialBuffer[3] );
	
        p = ( int * ) ( & serialBuffer[ 1 ] );

	return ( ( 0 + p[ 0 ] ) & 0xff ) ;
}


/*
=============================================
Sec 1.0 
=============================================
*/

void ledRGB( int fd ){

	setModeISS_setPins(fd,0);
	sleep(1);
	setModeISS_setPins(fd,1);
	sleep(1);
	setModeISS_setPins(fd,2);
	sleep(1);
	setModeISS_setPins(fd,4);
	sleep(1);
	setModeISS_setPins(fd,8);
	sleep(1);
	setModeISS_setPins(fd,8+2);
	sleep(1);
	setModeISS_setPins(fd,2);
	sleep(1);
	setModeISS_setPins(fd,4+2);
	sleep(1);
	setModeISS_setPins(fd,4);
	sleep(1);
	setModeISS_setPins(fd,8+4);
	sleep(1);
	setModeISS_setPins(fd,8);
	sleep(1);
	setModeISS_setPins(fd,0);
	sleep(1);
	setModeISS_setPins(fd,8+4+2);
	sleep(1);
}

/*
=============================================
Sec 1.0 
=============================================
*/

void sendMAX2719( int fd , int cmd ){
    char ip;
    int bit, sbit, cnt ,cmd2;
    cmd2 =cmd;
    printf("\n=========\nMAX2719: %04X  \n",cmd);
    setModeISS_setPins(fd, MAX2719_CS	);
    //usleep( MAX2719_CLK_time  );
    DELAY
    setModeISS_setPins(fd, 0	);
    //	usleep( MAX2719_CLK_time  );
    DELAY	
//    setModeISS_setPins(fd, MAX2719_CLK	);
    //	usleep( MAX2719_CLK_time  );
//    DELAY
    setModeISS_setPins(fd, 0	);
    //	usleep( MAX2719_CLK_time  );
    DELAY
    for( cnt = 0 ; cnt < 16 ; cnt++ ){
      bit = 1 << 15 ;
      if ( cmd2 & bit ){ 
	sbit = MAX2719_DIN;
      } else {
	sbit = 0;
      }
      //printf("bit: %x %06X %06X \n",cnt, sbit,cmd2);

      // bit = bit + bit;  
      cmd2 = cmd2+cmd2;
      // clk: ____- _- _- _- _- _-
      // DIN:    == == == == == == 
      // CS:  --___________________---
	
      // set up data
      setModeISS_setPins(fd,	  	      sbit  		);
      //usleep(MAX2719_CLK_time  );
      DELAY
    
      // clock bit in   
      setModeISS_setPins(fd,MAX2719_CLK + sbit 	);
      //usleep(MAX2719_CLK_time  );
      DELAY
      // reset clock
      setModeISS_setPins(fd,              sbit 	);
      //usleep(MAX2719_CLK_time );
	  DELAY
    }  
  	
    //usleep(MAX2719_CLK_time );
    DELAY
    // load data
    //printf("loading data: %02X %02X \n",cmd,cmd2);
	
    //setModeISS_setPins(fd, MAX2719_CLK +sbit + MAX2719_CS   );
    //usleep(MAX2719_CLK_time );
    DELAY 
    setModeISS_setPins(fd,  MAX2719_CS   );
    //usleep(MAX2719_CLK_time );
	DELAY
	setModeISS_setPins(fd,  MAX2719_CS   );
	//usleep(MAX2719_CLK_time );
	DELAY
	//printf("\n");
	DELAYL
	//usleep(100000 divt  );
	//ip = getchar();

}


void sendMAX2719_segs( int fd , int cmd ){
  	  setModeISS_setIOmode( 	  fd, 0x00 );
	  setModeISS_setIOchangemode( fd, 0x00 );
	  sendMAX2719( fd , 0x0B07 ); // Number of digits
	  sendMAX2719( fd , 0x0900 ); // decode mode
	  sendMAX2719( fd , 0x0C01 ); // ShutDown 0c01 is normal operation

}
	

void sendMAX2719_segs_blank( int fd , int cmd ){
  	  setModeISS_setIOmode( 	  fd, 0x00 );
	  setModeISS_setIOchangemode( fd, 0x00 );
	  sendMAX2719( fd , 0x0C01 ); // ShutDown 0c01 is normal operation
	  sendMAX2719( fd , 0x0B07 ); // Number of digits
	  sendMAX2719( fd , 0x0900 ); // decode mode
	  sendMAX2719( fd , 0x0A03 ); // intensity
	  sendMAX2719( fd , 0x0C00 ); // ShutDown 0c00 is shut down

	  sendMAX2719( fd , 0x0100 ); // digit 0
	  sendMAX2719( fd , 0x0200 ); // digit 0
	  sendMAX2719( fd , 0x0300 ); // digit 0
	  sendMAX2719( fd , 0x0400 ); // digit 0

	  sendMAX2719( fd , 0x0500 ); // digit 0
	  sendMAX2719( fd , 0x0600 ); // digit 0
	  sendMAX2719( fd , 0x0700 ); // digit 0
	  sendMAX2719( fd , 0x0800 ); // digit 0
	  sendMAX2719( fd , 0x0C01 ); // ShutDown 0c01 is normal operation

}


void sendMAX2719_help( int fd , int cmd ){
  	  setModeISS_setIOmode( 		fd, 0x00 );
	  setModeISS_setIOchangemode( fd, 0x00 );
	  sendMAX2719( fd , 0x0C01 ); // ShutDown 0c01 is normal operation
	  sendMAX2719( fd , 0x0B07 ); // Number of digits
	  sendMAX2719( fd , 0x0900 ); // decode mode
	  sendMAX2719( fd , 0x0A03 ); // intensity
	  sendMAX2719( fd , 0x0C01 ); // ShutDown 0c00 is shut down

	  sendMAX2719( fd , 0x0B07 ); // Number of digits
	  sendMAX2719( fd , 0x09ff ); // decode mode
	  
	  sendMAX2719( fd , 0x080C ); // digit H
      sendMAX2719( fd , 0x070B ); // digit E
	  sendMAX2719( fd , 0x060D ); // digit L
      sendMAX2719( fd , 0x050E ); // digit P

	  sendMAX2719( fd , 0x040F ); // digit  
	  sendMAX2719( fd , 0x030A ); // digit -
	  sendMAX2719( fd , 0x0C01 ); // ShutDown 0c01 is normal operation

      sleep(2);

	
}

void sendMAX2719_cmds( int fd , int list, int *cmds ){
  int index = 0;
  setModeISS_setIOmode( 		fd, 0x00 );
  setModeISS_setIOchangemode( fd, 0x00 );
  sendMAX2719( fd , 0x0C01 ); // ShutDown 0c01 is normal operation
  sendMAX2719( fd , 0x0F00 ); // ShutDown 0c01 is normal operation

  while( cmds[ index ] != -1){
    sendMAX2719( fd , cmds[index++] ); // ShutDown 0c01 is normal operation
  }
  sleep(3);
}

void sendMAX2719xyz( int fd , int x , int y, int z ){ ;  // set LED on off
  int bits[] = { 1,2,4,8,0x10,0x20,0x40,0x80 };
  /* we really need a graphics memory */

  y++;
  printf("  %8x \n", 0x0100 * y + bits[ x ] );
  sendMAX2719( fd  , 0x0100 * (y) + bits[ x ] ); // digit 0

}


