

#ifndef _XTAL_FREQ
 // Unless specified elsewhere, 4MHz system frequency is assumed
 #define _XTAL_FREQ 20000000
#endif


#include	<htc.h>
#include	"lcd.h"

#define	LCD_RS 	RB5
#define LCD_EN 	RB4
#define	LCD_BL	RC1


#define LCD_DATA	PORTB

#define	LCD_STROBE()	((LCD_EN = 1),(LCD_EN=0))

/* write a byte to the LCD in 4 bit mode */

void
lcd_write(unsigned char c)
{	
     unsigned char x=0,y=0;
	 x =((c<<3)&0b10000000);
	 x|=((c<<1)&0b01000000);
	 x|=((c>>1)&0b00100000);
	 x|=((c>>3)&0b00010000);
	 y =((c>>3)&0b00000001);
	 y|=((c>>1)&0b00000010);
	 y|=((c<<1)&0b00000100);
	 y|=((c<<3)&0b00001000);	
	
	__delay_us(40);
	LCD_DATA = ( x & 0x0F );	//felső 4 bit
	LCD_STROBE();
	LCD_DATA = ( y & 0x0F );	//alsó 4 bit
	LCD_STROBE();
}

/*
 * 	Clear and home the LCD
 */

void
lcd_clear(void)
{
	LCD_RS = 0;
	lcd_write(0x1);
	__delay_ms(2);
}

/* write a string of chars to the LCD */

void
lcd_puts(const char * s)
{
	LCD_RS = 1;	// write characters
	while(*s)
		lcd_write(*s++);
}

/* write one character to the LCD */

void
lcd_putch(char c)
{
	LCD_RS = 1;	// write characters
	lcd_write( c );
}


/*
 * Go to the specified position
 */

void
lcd_goto(unsigned char pos)
{
	LCD_RS = 0;
	lcd_write(0x80+pos);
}
	
/* initialise the LCD - put into 4 bit mode */
void
lcd_init()
{
	char init_value;

	ADCON1 = 0x06;	// Disable analog pins on PORTA

	init_value = 0xC;	//ide 0x3 kellene, de a lábkiosztás miatt
	TRISC=0;			//meg kell fordítani
	TRISB=0;
	LCD_RS = 0;
	LCD_EN = 0;
//	LCD_RW = 0;
	
	__delay_ms(15);	// wait 15mSec after power applied,
	LCD_DATA	 = init_value;
	LCD_STROBE();
	__delay_ms(5);
	LCD_STROBE();
	__delay_us(200);
	LCD_STROBE();
	__delay_us(200);
	LCD_DATA = 0x4;	// Itt is meg kell fordítani
	LCD_STROBE();

	lcd_write(0x28); // Set interface length 2 lines
	lcd_write(0xc); // Display On, Cursor On, Cursor Blink
	lcd_clear();	// Clear screen
	lcd_write(0x6); // Set entry Mode
	LCD_BL=1;
}
