#include <fx2.h>
#include <fx2_regs.h>

extern void FX2_Delay( WORD ms);

extern void lcd_44780_write_ctrl(	unsigned char value);
extern void lcd_44780_write_data(	unsigned char value);
extern void lcd_44780_write_led(	BYTE n, BYTE v);

code BYTE bin2hex[16] = 
{
  0x30, 0x31, 0x32, 0x33, 0x34, 		// 0 - 4
  0x35, 0x36, 0x37, 0x38, 0x39,			// 5 - 9
  0x41, 0x42, 0x43, 0x44, 0x45, 0x46	// A - F
};

void lcd_44780_init()
{
 	lcd_44780_write_ctrl( 0x38); FX2_Delay(5);
 	lcd_44780_write_ctrl( 0x0F); FX2_Delay(5);
 	lcd_44780_write_ctrl( 0x01); FX2_Delay(5);
 	lcd_44780_write_ctrl( 0x06); FX2_Delay(5);
 	lcd_44780_write_ctrl( 0x0C); FX2_Delay(1);

 	lcd_44780_write_ctrl( 0x40 | 0x80); FX2_Delay(1);
}

void lcd_44780_gotoxy( BYTE x, BYTE y)
{
	BYTE cmd;
	
	cmd = 0x80;
	cmd = cmd | ((y & 0x01) << 6);
	cmd = cmd | ((x & 0x07));
	
	lcd_44780_write_ctrl(cmd); 
	FX2_Delay(1);
}

void lcd_44780_putled( BYTE n, BYTE v)
{
	lcd_44780_write_led(n,v);
}

void lcd_44780_putc( char c)
{
	lcd_44780_write_data( c);
	FX2_Delay(1);
}

void lcd_44780_puts( char *s)
{
	if(s)
		while( *s)
			lcd_44780_putc(*s++);
}

void lcd_44780_putx2( BYTE x)
{
	BYTE x1 = bin2hex[(x >> 4) & 0x0F];
	BYTE x2 = bin2hex[(x >> 0) & 0x0F];
	
	lcd_44780_write_data(x1); FX2_Delay(2);
	lcd_44780_write_data(x2); FX2_Delay(2);
}
