/******************************************************************************
*  LPC122x I2C demoprogram for MicroCore48 rev B board (by Paul Seerden)
*
*  1. Use Systick timer to generate a 10 msec timer tick (interrupt driven).
*  2. Run leds connected to PCA9500 using interrupt driven I2C driver.
*******************************************************************************/

#include "LPC122x.h"                           // LPC122x definitions
#include "i2c.h"

static I2C_MSG iopMsg;                         // Message for PCA9500 IO port
static BYTE    iopBuf[1];                      // I2C PCA9500 data buffer

volatile LONG SysTickCnt;                      // System Tick Counter


void SysTick_Handler (void)
{                                              // SysTick Interrupt Handler (1ms)
  SysTickCnt++;
}

static void RunLeds(void)
{
    iopMsg.address = SLA_PCA9500_IO;
    iopMsg.buf     = iopBuf;
    iopMsg.nrBytes = 1;
    iopMsg.next    = 0;

    switch (iopBuf[0])                         // run the I2C IOport leds
    {
      case 0x7f: iopBuf[0] = 0xfe;   break;
      case 0xbf: iopBuf[0] = 0x7f;   break;
      case 0xdf: iopBuf[0] = 0xbf;   break;
      case 0xef: iopBuf[0] = 0xdf;   break;
      case 0xf7: iopBuf[0] = 0xef;   break;
      case 0xfb: iopBuf[0] = 0xf7;   break;
      case 0xfd: iopBuf[0] = 0xfb;   break;
      case 0xfe: iopBuf[0] = 0xfd;   break;
      default:   iopBuf[0] = 0xfe;   break;
    }
    I2C_Transfer(&iopMsg);
/*
    switch (I2C_Transfer(&iopMsg))
    {
      case I2C_OK                 : break;
      case I2C_NO_DATA            : PrintString(bufempty);  break;
      case I2C_NACK_ON_DATA       : PrintString(nackdata);  break;
      case I2C_NACK_ON_ADDRESS    : PrintString(nackaddr);  break;
      case I2C_TIME_OUT           : PrintString(timedout);  break;
      default                     : PrintString(unknowst);  break;
    }
*/
}

void Delay (unsigned long tick)
{
  unsigned long systickcnt;

    systickcnt = SysTickCnt;
    while ((SysTickCnt - systickcnt) < tick) __wfi();
}

int main (void)
{
//    SystemInit();
    LPC_SYSCON->SYSAHBCLKCTRL |= (1<<16);      // enable AHB clock to the IOCON
    SysTick_Config(SystemCoreClock/100);       // Generate interrupt each 10 ms

    I2C_Init();                                // initialize I2C bus

    while (1)
    {
        Delay(20);                             // delay 200ms
        RunLeds();                             // run leds on PCA9500 IO port
    }
}
