/*
 * i2c.c - writes VID:PID to the 24LC128 eeprom on CY7C68013 board
 *
 * Some cheap logic analyser modules may need the VID:PID reprogrammed.
 * These may have an 24LC02 iic eeprom to store the VID:PID
 * 
 * default:
 * 04b4:8613 Cypress Semiconductor Corp. CY7C68013 EZ-USB FX2 USB 2.0 board.
 * 
 * needs the VID:PID below so it can be used with sigrok
 * 0925:3881 Lakeview Research Saleae Logic
 *  
 * The chip is used in cheap logic analyser modules that offer 8 bit 24Ms
 * which can be used with sigrok https://sigrok.org/
 * 
 * These may need the VID:PID remapped to 0925:3881 for fx2lafw
 * https://sigrok.org/wiki/Lcsoft_Mini_Board
 * 
 * Doug Rice modified i2c.c to write and read IIC ROM and printout to serial.
 * 
 * Original i2c from https://github.com/djmuhlestein/fx2lib
 * This is useful for building, but the examples don't all work on my boards:-
 *
 * This is really useful. Problems with __ in include files.
 * https://www.triplespark.net/elec/periph/USB-FX2/software/ 
 * 
 * SDCC may have a converter file.
 * 
 * This WIKI is useful.
 * http://www.geeetech.com/wiki/index.php/CY7C68013 - two links
 * https://www.geeetech.com/wiki/index.php/CY7C68013
 *
 * Download and install Using https://github.com/djmuhlestein/fx2lib
 * I modified the i2c example to this file.
 * 
 * pi@raspberrypiwww:~/Desktop/fx2lib-master/examples/i2c
 * 
 * The chip has iic on its own pins.
 * 
 * this writes to i2c eeprom but if you overwrite the first byte it 
 * does not work.
 *  
 * fx2load -v 0x0925 -p 0x3881 build/i2c.bix
 * Put device in reset
 * wrote 1 bytes
 * loading bix file of length: 3038
 * wrote 1024 bytes
 * wrote 1024 bytes
 * wrote 990 bytes
 * Set device to run
 * wrote 1 bytes
 * 
 * But it does not work with the default address if the eeprom is disabled
 * 
 * I had to use this to 
 * pi@raspberrypi:~/Desktop/cypress/cycfx2prog-0.47 $ ./cycfx2prog prg:i2c.ihx
 * pi@raspberrypi:~/Desktop/cypress/cycfx2prog-0.47 $ ./cycfx2prog run
 * 
 * This is really useful. Problems with __ in include files.
 * https://www.triplespark.net/elec/periph/USB-FX2/software/ 
 * 
 * idea: use this program to write the VID:PID to the iic eeprom.
 * 
 * use lsusb to list the VID:PID
 * 
 * If it shows default VID:PID 04b4:8613,
 * build this program
 *   make
 * Then upload and run this code, 
 *   make run
 * 
 *  ./cycfx2prog  prg:i2c.ihx run 
 * 
 *  poll io using delay:200 dram:0xE000,0x2
 * 
 *  ./cycfx2prog prg:build/i2c.ihx  run delay:200 dram:0xE000,0x2
 * 
 * move ROM's link while running.
 *
 *  ./cycfx2prog  delay:200 dram:0xE000,0x2
 *  
 * This program tries to write the VID:PID in a loop.
 * 
 * It will fail to write to the IIC, 
 * until the link is moved to set the eeprom address to 0x51. 
 * 
 * The eeprom is found and the write is successful.
 * 
 * Turn off and on and lsusb should show updated VID:PID
 * 
 * Details of the boards can be found at:
 * http://www.geeetech.com/wiki/index.php/CY7C68013 - two links
 * 
 * On light blue board with white writing and no LEDS link pulls A0 to 3V, remove link to float A0 pin.
 * Bus 004 Device 007: ID 04b4:8613 Cypress Semiconductor Corp. CY7C68013 EZ-USB FX2 USB 2.0 Development Kit
 * 
 * On dark blue board with black writing with two LEDS lin insert link to set eepro @ 0xA0 instead of 0xA1 
 * Bus 004 Device 017: ID 04b4:8613 Cypress Semiconductor Corp. CY7C68013 EZ-USB FX2 USB 2.0 Development Kit
 * 
 * 
 * I modified I2c.c to read IIC rom and printout to serial.
 * 
 * USB Boot Methods
 * 
 * During the power-up sequence, internal logic checks the I2C port
 * for the connection of an EEPROM whose first byte is either 0xC0
 * or 0xC2. If found, it uses the VID/PID/DID values in the EEPROM
 * in place of the internally stored values (0xC0), or it boot-loads the
 * EEPROM contents into internal RAM (0xC2). If no EEPROM is
 * detected, FX2LP enumerates using internally stored descriptors.
 * The default ID values for FX2LP are VID/PID/DID (0x04B4,
 * 0x8613, 0xAxxx where xxx = Chip revision)[4].
 * 
 * 
 * The boards have a link on A0 that moves it's address.
 * The logic analyser may have a 24LC02 with the wrong VID:PID
 *
 * The I2C has a link on A0
 * 
 * The chip boots from I2C @ 0x51
 * 
 * If the link is not correct it prevents the boot, the I2C address is 0x50
 *
 * The boot looks for the iic eeprom at addr: 0x51  
 * 
 * One board needs the link, the other board does not.
 *  
 * This can read and write i2c chip. 
 * 
 * To use the board as a logic analyser the iic chip needs
 * 
 * IIC rom:
 * C0 25 09 81 38 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 
 *
 * To restore the VID:PID change link so lsusb lists default PID
 *  
 * Bus 002 Device 008: ID 04b4:8613 Cypress Semiconductor Corp. CY7C68013 EZ-USB FX2 USB 2.0 Development Kit
 * 
 * compile and upload this file and let it run.
 * 
 * make run
 * 
 * The Program is running trying to write to IIC chip, 
 * 
 * restore link.
 * 
 * power cycle board and do lsusb
 * 
 * Bus 002 Device 009: ID 0925:3881 Lakeview Research Saleae Logic
 * 
 * 
 * lsusb
 * 
 * On light blue board with white writing and two LEDS link pulls low remove link for
 * Bus 004 Device 007: ID 04b4:8613 Cypress Semiconductor Corp. CY7C68013 EZ-USB FX2 USB 2.0 Development Kit

 * On dark blue board with black writing with two LEDS lin insert link to get  
 * Bus 004 Device 017: ID 04b4:8613 Cypress Semiconductor Corp. CY7C68013 EZ-USB FX2 USB 2.0 Development Kit
 *
 * If the default PID the the iic could be at 0x50.
 * The light blue board without the leds floats the A0 pin when removed.      addr=?
 * The dark  blue board with the leds pulls A0 down when the link is removed. addr= 0x50
 * 
 * Alternativly upload program using default VID:PID with iic chip address not 0x51.
 *  
 * run code which tries to write to iic chip
 * restore link to enable iic chip
 * or
 *  
This WIKI is useful.
http://www.geeetech.com/wiki/index.php/CY7C68013 - two links
https://www.geeetech.com/wiki/index.php/CY7C68013

The is useful for building, but the examples don't work:-
https://github.com/djmuhlestein/fx2lib

This is really useful. Problems with __ in include files.
https://www.triplespark.net/elec/periph/USB-FX2/software/ 

 * If you change the first 8 bytes of the eeprom away from "C0 25 09 81 38 00 00 00 " make load does not work.
 *
 * IIC rom:
 *
 * C0 25 09 81 38 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 
 *
 * Use one of these to load this program which writes to the eeprom.
 * ./cycfx2prog  prg:i2c.ihx run 
 * 
 * or if eeprom already programmed use lsusb and modify one of these to suit. 
 * sudo ./cycfx2prog  -d=001.011   prg:build/i2c.ihx run 
 *      ./cycfx2prog -id=0925:3881 prg:build/i2c.ihx run
 *      ./cycfx2prog -id=0925:3881 prg:build/i2c.ihx run delay:200 dram:0xE000,0x2
 * 
 * IO at absolute address, so it can be polled.
 * 
 * ./cycfx2prog prg:build/i2c.ihx  run delay:200 dram:0xE000,0x2
 * 
 * 	__xdata __at 0xE000 volatile int io = 0x1234;
 * 
 * ./cycfx2prog prg:build/i2c.ihx  run delay:200 dram:0xE000,0x2
 * 
 * 
 * pi@raspberrypi:~/Desktop/cypress/cycfx2prog-0.47 $ ./cycfx2prog -d=001.011 prg:i2c.ihx run
 *
 * devices boots and if eeprom does not start with C0 or C2 or eeprom not found, 
 * then the chip boots off the USB and cycfx2prog and upload and run a program.
 * If you upload this, and make sure it writes  "C0 25 09 81 38 00 00 00 " to eeprom this will
 * allow the fx2load to work again.
 *
 * Some of the examples that came with fx2lib did not work on my board
 * as they are written for another dev board.
 *
 * lights.h did not enable the ports to be outputs OEA = 0xFF;	
 *
 * the i2c.c program needed some retiming to get it to work.
 * The serial port is not avaiable so this program has a bit-banged putc to allow debug
 * 
 *pi@raspberrypiwww:~/Desktop/fx2lib-master/examples/i2c/Makefile:- 
FX2LIBDIR=../..
BASENAME = i2c
SOURCES=i2c.c
DSCR_AREA=
INT2JT=
include $(FX2LIBDIR)/lib/fx2.mk	
#VID?=0x0925
#PID?=0x3881


run: 
	./cycfx2prog --list --help prg:build/i2c.ihx run
	./cycfx2prog prg:build/i2c.ihx run delay:200 dram:0xE000,0x8 delay:2000 dram:0xE000,0x8
	./cycfx2prog delay:2000 dram:0xE000,0x8

run0925: 
	./cycfx2prog --help --list -id=0925.3881 prg:build/i2c.ihx run
	./cycfx2prog -id=0925.3881 prg:build/i2c.ihx run  delay:200 dram:0xE000,0x8 delay:2000 dram:0xE000,0x8
	./cycfx2prog delay:2000 dram:0xE000,0x8


 * 
 * Copyright (C) 2009 Ubixum, Inc. 
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 **/


/*
 *********************************************
 * SEC 0 - Includes
 *********************************************
 */

#include <fx2regs.h>
#include <i2c.h>
#include <delay.h>



/*
 *********************************************
 * SEC 0 - defines
 *********************************************
 */

/* 1/50   = 20000us   		works */
/* 1/300  = 3333.33333333us   		works */

/* 1/1200 = 833us   		works */
/* 1/2400 = 416.666666667 	works */
/* 1/4800 = 208.333333333 	works */
/* 1/9600 = 104.166 		does not work */

#define BITDELAY 833

#define LED_ADDR 0x27

/*
 * 
 * The I2C has a link on A0
 * The chip boots from I2C @ 0x51
 * If the link is prevents the boot, the I2C address is 0x50
 *  
 */
#define I2C_ADDR 0x51

/*
 * DUMP IIC memory chip. 
 * Bus 001 Device 012: ID 0925:3881 Lakeview Research Saleae Logic
===
IIC rom:
C0 25 09 81 38 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 
*/ 

BYTE digits[] = { 0xc0, 0x25, 0x09, 0x81, 0x38, 0x00, 0x00, 0x00, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0  };

char * str="doug rice was here";
//#define DEBUG_I2C 1

#ifdef DEBUG_I2C
#define i2c_printf(...) printf(__VA_ARGS__)
#else
#define i2c_printf(...)
#endif

// xxd -i build/lights.iic
//unsigned char build_lights_iic[] = {
/*
BYTE * build_lights_iic = {
  0xc2, 0x25, 0x09, 0x81, 0x38, 0x00, 0x00, 0x04, 0x01, 0x53, 0x00, 0x00,
  0x35, 0x41, 0x00, 0x80, 0x01, 0xe6, 0x00, 0x00
};
*/
//unsigned int build_lights_iic_len = 356;

/* *********************************************** */
#include <stdbool.h>
#include <stdio.h>



/*
 *********************************************
 * SEC 0 - IO 
 *********************************************
 */

/*
 * IO at absolute address, so it can be polled.
 * 
 * ./cycfx2prog prg:build/i2c.ihx  run delay:200 dram:0xE000,0x2
 */

__xdata __at 0xE000 volatile int io = 0x1234;
__xdata __at 0xE002 volatile BYTE iostr[20] ;


/*
 *********************************************
 * SEC 0 - Serial using bitbang and timer
 *********************************************
 */

volatile unsigned char sendcounter;
volatile unsigned int senddata;
volatile _Bool sending;

void send_bit(void) __interrupt(3)
{
	//reload and count up to 0.
	// 2^16
	//
	// 1200 baud = 0.83ms
	// 
	// Count up from - 833 to 00
	// ticks at 1us ticks?
	//
	TH1 = ( 65536 - BITDELAY ) / 256;
	TL1 = ( 65536 - BITDELAY ) % 256;

	if(!sending)
		return;

	IOA = senddata & 1;
	senddata >>= 1;

	if(!--sendcounter)
	{
		sending = false;
		IE &= ~0x08;
	}
}

//int putchar(int c)
void putchar(char c)
{
	
	
	while(sending);
	// there is no UART on 56 pin device.
    // set up START bit,byte, stop bit
    // S01234567s 
	// use timer and interupt to clock out the bit
	// OR start and Stop bits    
	senddata = ( c << 1 ) | 0x200;
	sendcounter = 10; // send  START bit + 8 bits + stop bit
	sending = true;
	IE |= 0x08;

}



/*
 *********************************************
 * SEC 0 - iic functions
 *********************************************
 */

volatile __xdata BOOL cancel_i2c_trans;
#define nCHECK_I2C_CANCEL() if (cancel_i2c_trans) return TRUE
#define CHECK_I2C_CANCEL() if ( 1==0 ) return TRUE;

/**
 *
    1. Set START=1. If BERR=1, start timer*.
    2. Write the 7-bit peripheral address and the direction bit (0 for a write) to I2DAT.
    3. Wait for DONE=1 or for timer to expire*. If BERR=1, go to step 1.
    4. If ACK=0, go to step 9.
    5. Load I2DAT with a data byte.
    6. Wait for DONE=1*. If BERR=1, go to step 1.
    7. If ACK=0, go to step 9.
    8. Repeat steps 5-7 for each byte until all bytes have been transferred.
    9. Set STOP=1. Wait for STOP = 0 before initiating another transfer.
 **/
BOOL i2c_2write2 ( BYTE addr, WORD len, BYTE *addr_buf, WORD len2, BYTE* data_buf ) {
    
    WORD cur_byte;
    
    WORD total_bytes = len+len2; // NOTE overflow error?
    BYTE retry_count=200; // two tries to write address/read ack
    cancel_i2c_trans=FALSE;
    //BOOL wait=FALSE; // use timer if needed

    // 1. Set START=1. If BERR=1, start timer*.
    step1:
        CHECK_I2C_CANCEL();
        cur_byte=0;
        I2CS |= bmSTART;
        if ( I2CS & bmBERR ) {
            //i2c_printf ( "Woops.. need to do the timer\n" );
            delay(10); // way too long probably
            goto step1;
            }
      
    // 2. Write the 7-bit peripheral address and the direction bit (0 for a write) to I2DAT.
        I2DAT = addr << 1;
        
    // 3. Wait for DONE=1 or for timer to expire*. If BERR=1, go to step 1.
        while ( !(I2CS & bmDONE) && !cancel_i2c_trans);
        CHECK_I2C_CANCEL();
        if (I2CS&bmBERR) {
            //i2c_printf ( "bmBERR, going to step 1\n" );
            goto step1;
        }
    
    
    /* important add some delay */    
        delay(1);
        delay(10);
 
    // 4. If ACK=0, go to step 9.
    if ( !(I2CS & bmACK) ) {

        I2CS |= bmSTOP;
        while ( (I2CS & bmSTOP) && !cancel_i2c_trans);
        CHECK_I2C_CANCEL();
        --retry_count;
        if (!retry_count){
            //i2c_printf ( "No ack after writing address.! Fail\n");
            return FALSE;
        }
        delay(10);
        goto step1;
    }
    
    // 8. Repeat steps 5-7 for each byte until all bytes have been transferred.
    while ( cur_byte < total_bytes ) {

        // 5. Load I2DAT with a data byte.
        I2DAT = cur_byte < len ? addr_buf[cur_byte] : data_buf[cur_byte-len];
        ++cur_byte;
        // 6. Wait for DONE=1*. If BERR=1, go to step 1.
        while (!(I2CS&bmDONE) && !cancel_i2c_trans); CHECK_I2C_CANCEL();
        if ( I2CS&bmBERR ) {
         //i2c_printf ( "bmBERR on byte %d. Going to step 1\n" , cur_byte-1 );
         goto step1;
         //return FALSE;
        }
        // 7. If ACK=0, go to step 9.
        delay(1);
        if ( !(I2CS & bmACK) ) {
            I2CS |= bmSTOP;
            while ( (I2CS&bmSTOP) && !cancel_i2c_trans);
            //i2c_printf ( "No Ack after byte %d. Fail\n", cur_byte-1 );
            return FALSE; 
        }
    }

    
    // 9. Set STOP=1. Wait for STOP = 0 before initiating another transfer.
    //real step 9
    I2CS |= bmSTOP;
    while ( (I2CS & bmSTOP) && !cancel_i2c_trans);
    CHECK_I2C_CANCEL();

    return TRUE;

}

/*
 trm 13.4.4
 
    1. Set START=1. If BERR = 1, start timer*.
    2. Write the 7-bit peripheral address and the direction bit (1 for a read) to I2DAT.
    3. Wait for DONE=1 or for timer to expire*. If BERR=1, go to step 1.
    4. If ACK=0, set STOP=1 and go to step 15.
    5. Read I2DAT to initiate the first burst of nine SCL pulses to clock in the first byte from the slave.
    Discard the value that was read from I2DAT.
    6. Wait for DONE=1. If BERR=1, go to step 1.
    7. Read the just-received byte of data from I2DAT. This read also initiates the next read transfer.
    8. Repeat steps 6 and 7 for each byte until ready to read the second-to-last byte.
    9. Wait for DONE=1. If BERR=1, go to step 1.
    10. Before reading the second-to-last I2DAT byte, set LASTRD=1.
    11. Read the second-to-last byte from I2DAT. With LASTRD=1, this initiates the final byte read on
    the bus.
    12. Wait for DONE=1. If BERR=1, go to step 1.
    13. Set STOP=1.
    14. Read the final byte from I2DAT immediately (the next instruction) after setting the STOP bit. By
    reading I2DAT while the "stop" condition is being generated, the just-received data byte will be
    retrieved without initiating an extra read transaction (nine more SCL pulses) on the I²Cbus.
    15. Wait for STOP = 0 before initiating another transfer
*/

/*
  * timer should be at least as long as longest start-stop interval on the bus
  serial clock for i2c bus runs at 100khz by default and can run at 400khz for devices that support it
  start-stop interval is about 9 serial clock cycles
  400KHZ bit 0=100khz, 1=400khz
  
  how many cycles at XTAL cycles/second = 9 cycles at 400k (or 100k) cycles/second
  
  timeout = n i2c cycles / I2C cycles/sec = timeout seconds
          timeout seconds * XTAL cycles/sec = XTAL cycles
          9 / 400 (or 100) * (XTAL)
  
*/




BOOL i2c_2read2( BYTE addr, WORD len, BYTE* buf) {
    
    BYTE tmp;
    WORD cur_byte;
    
    cancel_i2c_trans=FALSE;
    //WORD timeout_cycles = (WORD)(9.0 * XTAL / I2CFREQ );
    
    // 1. Set START=1. If BERR = 1, start timer*.
    start:
        CHECK_I2C_CANCEL();
        cur_byte=0;        

        I2CS |= bmSTART;
/*        
        if ( I2CS & bmBERR ) {            
            //i2c_printf ( "Woops, step1 BERR, need to do timeout\n");
            delay(10); // NOTE way too long
            goto start;
        }
*/        
    // 2. Write the 7-bit peripheral address and the direction bit (1 for a read) to I2DAT.
        I2DAT = (addr << 1) | 1; // last 1 for read
    
    // 3. Wait for DONE=1 or for timer to expire*. If BERR=1, go to step 1.
		delay(1);
        while ( !(I2CS & bmDONE) && !cancel_i2c_trans )      ; 
        //CHECK_I2C_CANCEL();
/*
        while ( !(I2CS & bmDONE)  ); 
        CHECK_I2C_CANCEL();
        if ( I2CS & bmBERR )
            goto start;
*/            
            
    // 4. If ACK=0, set STOP=1 and go to step 15.
/*
        if ( !( I2CS & bmACK ) ) {
            I2CS |= bmSTOP;
            while ( (I2CS&bmSTOP) && !cancel_i2c_trans );
            return FALSE; 
        }
*/      
  
    // with only one byte to read, this needs set here.
    // (In this case, the tmp read is the 2nd to last read)
    if ( len==1 ) I2CS |= bmLASTRD; 
        
    // 5. Read I2DAT to initiate the first burst of nine SCL pulses to clock in the first byte from the slave.
    //    Discard the value that was read from I2DAT.
    tmp = I2DAT; // discard read
    

    //printf("len > (cur_byte +1) +" );

    delay(1);
    while (len > (cur_byte +1) ) { // reserve last byte read for after the loop
    //printf("len > (cur_byte +1) 0x02X\r\n", I2CS );    
        // 6. Wait for DONE=1. If BERR=1, go to step 1.
        // 9. Wait for DONE=1. If BERR=1, go to step 1.
        while ( !( I2CS&bmDONE ) && !cancel_i2c_trans)
        ; 
        //CHECK_I2C_CANCEL();
         
//        if ( I2CS&bmBERR ) goto start;

        // 10. Before reading the second-to-last I2DAT byte, set LASTRD=1.
        if (len==cur_byte+2) // 2nd to last byte
            I2CS |= bmLASTRD;
        
        // 7. Read the just-received byte of data from I2DAT. This read also initiates the next read transfer.
        // 11. Read the second-to-last byte from I2DAT. With LASTRD=1, this initiates the final byte read on
        //     the bus.
            buf[cur_byte++] = I2DAT;
                        
        // 8. Repeat steps 6 and 7 for each byte until ready to read the second-to-last byte.
    }

    
    //12. Wait for DONE=1. If BERR=1, go to step 1.
   //     while (!(I2CS&bmDONE) && !cancel_i2c_trans); CHECK_I2C_CANCEL();
//        if ( I2CS&bmBERR ) goto start;
    // 13. Set STOP=1.
        I2CS |= bmSTOP;
    // 14. Read the final byte from I2DAT immediately (the next instruction) after setting the STOP bit. By
    // reading I2DAT while the "stop" condition is being generated, the just-received data byte will be
    // retrieved without initiating an extra read transaction (nine more SCL pulses) on the I²Cbus.
        buf[cur_byte] = I2DAT; // use instead of buffer addressing so next instruction reads I2DAT

  
    while ( (I2CS&bmSTOP) && !cancel_i2c_trans); CHECK_I2C_CANCEL();

    return TRUE;
}









/*
 *********************************************
 * SEC 0 - main
 *********************************************
 */




/**
 * This is pretty much the same function that is provided as the dev_io example from Cypress
 * Except is uses i2c read and write functions not from their library
 **/
void main(void) {

    BYTE    num = 0;
	BYTE	kstates = 0xff;
	BYTE	display = 1;
    BYTE 	count = 0;
	BYTE 	cnt=0x80;

	unsigned long int i = 0;
	//int count;

    OEA=0xFF;
    IOA=0x00;
    // delay(500);

	// Configure timer for 1200 baud
	TH1 = (65536 - 833) / 256;
	TL1 = (65536 - 833) % 256;
	TMOD = 0x10;
	IE |= 0x80;
	TCON |= 0x40; // Start timer
	//OEA=0x01; // port A as output

	iostr[0]=' ';
	iostr[1]=' ';
	iostr[2]=' ';
	iostr[3]=' ';
	iostr[4]=' ';
	iostr[5]=' ';

  while(1){

	int c =0	;

/*
pi@raspberrypi:~/Desktop/cypress/cycfx2prog-0.47 $ lsusb
Bus 002 Device 002: ID 0bda:0316 Realtek Semiconductor Corp. 
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 008: ID 138a:0097 Validity Sensors, Inc. 
Bus 001 Device 007: ID 5986:111c Acer, Inc 
Bus 001 Device 006: ID 8087:0a2b Intel Corp. 
Bus 001 Device 005: ID 0781:5573 SanDisk Corp. 
Bus 001 Device 004: ID 058f:9540 Alcor Micro Corp. AU9540 Smartcard Reader
Bus 001 Device 012: ID 0925:3881 Lakeview Research Saleae Logic
Bus 001 Device 002: ID 067b:2303 Prolific Technology, Inc. PL2303 Serial Port
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
pi@raspberrypi:~/Desktop/cypress/cycfx2prog-0.47 $ ls
*/


/* this writes to i2c eeprom but if you overwrite the first byte 
 * fx2load -v 0x0925 -p 0x3881 build/i2c.bix
Put device in reset
wrote 1 bytes
loading bix file of length: 3038
wrote 1024 bytes
wrote 1024 bytes
wrote 990 bytes
Set device to run
wrote 1 bytes
* 
* 
* I had to use this to 
* pi@raspberrypi:~/Desktop/cypress/cycfx2prog-0.47 $ ./cycfx2prog prg:i2c.ihx
* pi@raspberrypi:~/Desktop/cypress/cycfx2prog-0.47 $ ./cycfx2prog run
*/

// set up to write to i2c eeprom 
    count     = 0x00;
    /* start Address */
	digits[0] = 0x00;
	digits[1] = 0x00;

/* following bytes to write to */

/*
===
IIC rom:
C0 25 09 81 38 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 
----
*/

/* You need these for fx2load to work
 * I tried using fx2load using the default vid:pid, but I needed
 * cycfx2prog-0.47 to boot load a program to write to the eeprom.
 *
  	digits[2] = 0xC0;
	digits[3] = 0x25;
	digits[4] = 0x09;
	digits[5] = 0x81;
	digits[6] = 0x38;
	digits[7] = 0x00;
	digits[8] = 0x00;
	digits[9] = 0x00;
	* 
*/


/* logic analyser VID:PID */

   	digits[2] = 0xC0;
	digits[3] = 0x25;
	digits[4] = 0x09;
	digits[5] = 0x81;
	digits[6] = 0x38;
	digits[7] = 0x00;
	digits[8] = 0x00;
	digits[9] = 0x00;


	/* write the ADDR in the 24LC128 */		
/*	
	OEA = 0xFF;	
    IOA = 0x00;	
    				
	OEB = 0xFF;	
    IOB = 0x00;	
*/
    /* write two digit address + 10 data bytes */		

/* 
 * 
 * 24LC128 has two ADDR,  ADDRH and ADDRL set to 0 
 * 24LC02  has one ADDR set to 0
 * 
 * If you program the 24LC02 assuming 24LC128, the data will start 00
 */ 

/*24LC128:Page Write START,ControlByte,addr,addr,data, data, data, data, data, data, data, stop */
//    if ( i2c_2write2 ( I2C_ADDR, 2, &digits[0], 5, &digits[2] )){

	/*24LC02 - 256 bytes*/	
	/*24LC02:Page Write START,ControlByte,addr,data, data, data, data, data, data, data, stop */

    if ( i2c_2write2 ( I2C_ADDR, 1, &digits[0], 5, &digits[2] )){
		/* successful - set LEDS and memory at an absolute address */
		IOA = 0x3;
		IOA = 0x3;
		io = 0xAAAA;
	    delay(500);
        IOA = 0x00;	
        IOB = 0x00;	
	    delay(300);
	    iostr[0]=' ';
	    iostr[1]='O';
	    iostr[2]='K';
	    iostr[3]=' ';
	    iostr[4]=' ';
	    iostr[5]=' ';	    
	} else {
		/* NAK - set LEDS and memory at an absolute address */
		IOA = 0x1;		
		IOB = 0x1;		
		io = 0x5555;
	    iostr[0]=' ';		
	    iostr[1]='n';
	    iostr[2]='a';
	    iostr[3]='k';
	    iostr[4]=' ';
	    iostr[5]=' ';
	    iostr[6]=' ';
	}	
	delay(100);


/* 
 * I used bit banged serial to debug and get the iic to work. 
 * 
 */

//LCD_ADDR
/*
	printf("IIC rom:\n\r" );
	for( count = 0; count < 32; count++)
	{
		buttons=0;
		i2c_2read2 ( BTN_ADDR, 1, &buttons ) ;	 
		printf("%02X ",buttons );
    }
    printf("\n\r IOA: %02X  IOB: %02X  IOC: %02X  IOD: %02X \n\r----\n\r",IOA,IOB,IOC,IOD );
    printf("\n\r----\n\r" );
*/
  }
}


