//PROVATO SU 16F88 - LCD 162D (RS COMP)

#include <pic.h>
const char *TopMessage = "    PIC MCU     ";
const char *BotMessage = "  Evil_Genius   ";
const char n_bit = 8;  //*********************************

#define E  RA4                  
#define RS RA3


void delay(int n) 
{
	n=60*n; //per ottenere in millisecondi
	while(n--);
	return;
}

LCDWrite(int LCDData, int RSValue)
{
	if(n_bit==4) {
	    //4 BIT MODE
	    PORTB = (LCDData >> 4) & 0x0F;  //  Get High 4 Bits for Output
	    RS = RSValue;
	    E = 1;  
		delay(5);
		E = 0;              //  Toggle the High 4 Bits Out
	
	    PORTB = LCDData & 0x0F;     //  Get Low 4 Bits for Output
	    RS = RSValue;
	    E = 1;  
		delay(5);
		E = 0;              //  Toggle the Low 4 Bits Out
}
	if(n_bit==8) {
		    //8 BIT MODE
		RS = RSValue;
		PORTB = LCDData;
	    E = 1;  
		delay(5);
		E = 0;          
		delay(5);
	}
}  //  End LCDWrite



main()
{
	unsigned char i;
	IRCF2=1;IRCF1=1;IRCF0=1; //Internal oscill freq. = 8 MHz

	SCS1=0;SCS0=0;
	GIE=1;

	T0CS=0;     			//il clock di TMR0 è Fosc/4
	PSA=0;					//viene usato il prescaler
	PS2=1; 
	PS1=1; 
	PS0=1;  	//il prescaler viene impostato a 256************
	TMR0IE=0;			//mascheramento l'IRQ di TMR0;
	TMR0=0;

	TRISA=0;
	ANSEL=0;
	PORTA=0;
    TRISB = 0;                  //  All of PORTC are Outputs
    PORTB = 0;                  //  Start with Everything Low
	delay(200);
	RS=0;
	for (i = 0; i < 3; i++) {  //  Start Initialization Process (3 volte)
	    PORTB = 0x30;                  
	    E = 1;  
	    delay(5);
		E = 0;              //  Send Reset Command
		delay(5);
	}
	if(n_bit==4) 
    	LCDWrite(0b00101100, 0);    //  4 bit, 2 lines, 5x10 dot
	if(n_bit==8) 
    	LCDWrite(0b00111100, 0);    //  8 bit, 2 lines, 5x10 dot
    LCDWrite(0b00001000, 0);    //  Display off
    LCDWrite(0b00000001, 0);    //  Clear LCD 
    LCDWrite(0b00000110, 0);    //  Entry mode set (increase, not shifted)
    LCDWrite(0b00000110, 0);    //  Move Cursor After Each Character
    LCDWrite(0b00001110, 0);    //  Turn On LCD and Enable Cursor

	i=0;
	while(*(TopMessage+i)) 
        LCDWrite(*(TopMessage + i++), 1);

    LCDWrite(0b11000000, 0);    //  Move Cursor to the Second Line

	i=0;
	while(*(BotMessage+i)) 
        LCDWrite(*(BotMessage + i++), 1);

	while(1);

}  //  End cLCD

