
#include <at89x52.h>
#include <stdio.h>
#include <string.h>

#define LCD_RS              P3_6
#define LCD_E               P3_7
#define LCD_BUS_PORT        P0

//Delay in ms (at 12MHZ Crystal)
void delay_ms(unsigned  int ms) {
	TMOD = (TMOD & 0xF0) | 0x01;  //Set Timer0 to mode 1 (16 bit counter)
	TR0 = 1;                      //Start the timer]

	while (ms > (unsigned char) 64) {
		TH0 = 0x06; TL0 = 0x00;   //Reset the timer count to -64000 (Will take 64ms to complete)
		TF0 = 0;                  //Reset overflow flag
		while (TF0 != 1);         //Wait until Timer1 overflows

		ms -= (unsigned char) 64;
	}
	while (ms != (unsigned char) 0) {
		TH0 = 0xFC; TL0 = 0x18;   //Reset the timer count to -1000 (Will take 1ms to complete)
		TF0 = 0;                  //Reset overflow flag
		while (TF0 != 1);         //Wait until Timer1 overflows
		
		ms--;
	}

	TR0 = 0;                      //Stop the timer
}



void E_clk() {
	delay_ms(1);
	LCD_E =0; 
	delay_ms(1);
	LCD_E=1;
	delay_ms(1);
	LCD_E =0; 
}

void main() {
	unsigned char buffer[] = "Hello world";
	unsigned char *p;
	unsigned int i;
	
	//Toggle led 
	for (i = 0; i < 2; i++) {
		P2_7 = 1;
		delay_ms(50);
		P2_7 = 0;
		delay_ms(50);
	}

	//Power on
	//Wait more than 15 msecs after power is applied.
	delay_ms(40); 

	LCD_RS = 0; //instructions

	LCD_BUS_PORT = 0x30;
	E_clk();
	delay_ms(10);

	LCD_BUS_PORT = 0x30;
	E_clk();

	LCD_BUS_PORT = 0x30;
	E_clk();

	LCD_BUS_PORT = 0x20;
	E_clk();

	//0x28 (4Bit mode,2Lines,Small font)
	LCD_BUS_PORT = 0x20;
	E_clk();
	LCD_BUS_PORT = 0x80;
	E_clk();

	//0x08 (Display off)
	LCD_BUS_PORT = 0x00;
	E_clk();
	LCD_BUS_PORT = 0x80;
	E_clk();

	//0x01 (Clear the display)
	LCD_BUS_PORT = 0x00;
	E_clk();
	LCD_BUS_PORT = 0x10;
	E_clk();
	delay_ms(10);

	//0x06 (Entry mode - no shifting, auto increase)
	LCD_BUS_PORT = 0x00;
	E_clk();
	LCD_BUS_PORT = 0x60;
	E_clk();

	//0x0E (Display on)
	LCD_BUS_PORT = 0x00;
	E_clk();
	LCD_BUS_PORT = 0xE0;
	E_clk();

	LCD_RS = 1;


	
p = buffer;
	while (*p) {
		LCD_BUS_PORT = *p;
		E_clk();
		LCD_BUS_PORT = *p << 4;
		E_clk();

		p++;
	}
	


	while(1);
}
