#include "quattro_regs.h"
#include "8_x_6_charset.h"
/* LCD print call example:    lcd_print_crlf("Reduce Power    "); */

void delay(int delay);
void init_lcd(void);
void lcd_clear(void);
void lcd_putchar(unsigned char c);
void lcd_print_crlf(char *s);
void set_line(unsigned char line);
void i2c_write(unsigned data);
void page_delay(void);

#define CHAR_DELAY    500
#define BLINK_DELAY  2000
#define CLEAR_DELAY 50000
#define MAX_CHARS   16

#define ON 0
#define OFF 1

unsigned char line_ctr;
unsigned time_to_clear;

void delay(int delay)
{
   while ( delay )
   {
      delay--;
   }
}  /* delay */

void init_lcd(void)
{
   /* Enable I2C1 clock */
   *I2CCLK_CTRL = 0x1;
   *I2C1_CLK_CTRL_HI = 0x41;
   *I2C1_CLK_CTRL_LO = 0x41;
}  /* init_lcd */

void lcd_putchar(unsigned char c)
{
   int i;
   for ( i=0; i<6; i++ )
   {
      i2c_write(charset[(c-32)][i]);
   }
}  /* lcd_putchar */

void lcd_print_crlf(char *s)
{
  char CharCount = 0;

   if ( line_ctr > 4 )
   {
      line_ctr = 0;
   }
   set_line(line_ctr);
   while ( *s != 0 || CharCount < 16 )
   {
      lcd_putchar(*s++);
      CharCount++;
   }
   line_ctr++;
}  /* lcd_print_crlf */

void set_line(unsigned char line)
{
   i2c_write(0x17A);
   i2c_write((0x60+line));
   i2c_write(0x0);
}  /* set_line */

void lcd_clear(void)
{
   int i,j;
   for ( i=0; i<5; i++ )
   {
      set_line(i);
      for ( j=0; j<16; j++ )
      {
         lcd_putchar(0x20);
      }
   }
   set_line(0);
}  /* lcd_clear */

void i2c_write(unsigned data)
{
   *I2C1_TX = data;
   delay(CHAR_DELAY);
}

void page_delay(void)
{
   while ( time_to_clear-- )
   {
      if ( time_to_clear == 0 )
      {
         lcd_clear();
      }
      delay(250);
   }
   time_to_clear = CLEAR_DELAY;
}

