#include<reg51.h>
#include<absacc.h>
#define output P0
sbit EN=P2^6;
sbit RS=P3^7;
sbit RW=P3^6;

#define controlport P2
volatile char xdata OSC _at_ 0x800a;//register a
volatile char xdata UPDATE _at_ 0x800b;//register b
volatile char xdata SEC _at_ 0x8000;
volatile char xdata HR _at_ 0x8004;
volatile char xdata MIN _at_ 0x8002;
volatile char xdata DD _at_ 0x8007;
volatile char xdata MM _at_ 0x8008;
volatile char xdata YY _at_ 0x8009;

void bcdconvert(unsigned x);
void serialsend(unsigned x);
void Delay(unsigned int);
void lcd_write(unsigned char);
void delay(void);

unsigned char second,hour,minute,i,j,k;
unsigned char s1[15]=" TLN's Trainer ";//all these three	 
unsigned char s2[15]="   is ready    ";//comes on LCD
unsigned char s3[15]="   HH:MM:SS    ";
void main(void)
{
	TMOD=0x20;//serial communication settings
	TH1=0xfd;
	SCON=0x50;
	TR1=1;

	delay();//give RTC a startup delay of 200ms
	delay();

	OSC=0X2f;//to turn on the oscillator
	
	//lcd initialisation

	//lcd function set 2 line, 8 bit 5x7
	RS=0;
	lcd_write(0x38);

	//lcd function set 2 line, 8 bit 5x7
	RS=0;
	lcd_write(0x38);
	//display on , cursor underline
	RS=0;
	lcd_write(0x0e);

	//charcter entry. increment, display shift
	RS=0;
	lcd_write(0x06);

	//clear lcd
	RS=0;
	lcd_write(0x02);

	//CURSOR HOME
	RS=0;
	lcd_write(0x01);
	//------------------------------------------

	while(1){
					   
	//set display address line1
	RS=0;
	lcd_write(0x80);
	//writing text "TLN's Tainer" 
	for(j=0;j<15;j++)
	{
		RS=1;
		lcd_write(s1[j]);
	}
	delay();			   	
	
	//set display address line 2
	RS=0;
	lcd_write(0xC0);
	//writing text 	"is ready"
	for(i=0;i<15;i++)
	{
		RS=1;
		lcd_write(s2[i]);
	}
	delay();
	
	//clear lcd
	RS=0;
	lcd_write(0x01);
	delay();

	//set display address line 1
	RS=0;
	lcd_write(0x80);
	//writing text "HH:MM;SS"
	for(k=0;k<16;k++)
	{
		RS=1;
		lcd_write(s3[k]);
	}
	//read RTC when uip is low.
	while( OSC & 0x80 );
		
		second=SEC;
		hour=HR;
		minute=MIN;

		//set display address line 2
		RS=0;
		lcd_write(0xc0);
		//writing time.....
		bcdconvert(hour);
		serialsend(':'); 
		RS=1;
		lcd_write(':');

		bcdconvert(minute);
		serialsend(':');
		RS=1;
		lcd_write(':');

		bcdconvert(second);
		serialsend(0x0d);
		serialsend(0x0a);				  
	}

}
void bcdconvert(unsigned mybyte){
	//Read RTC and convert to ASQII
	//send it to LCD and serial Port
	unsigned  char x,y;
	x=mybyte&0x0f;
	x=x|0x30;
	y=mybyte&0xf0;
	y=y>>4;
	y=y|0x30;
	serialsend(y);
	RS=1;
	lcd_write(y);
	serialsend(x);
	RS=1;
	lcd_write(x);
	}
void serialsend(unsigned x){
	SBUF=x;	
	while(TI==0);
	TI=0;
	}

//delay 250 milli secondss appx.
void delay()
{
unsigned char a3,b1;
for(a3=0;a3<200;a3++)
	for(b1=0;b1<200;b1++);
return;
}

//lcd_write
void lcd_write(unsigned char ch)
{
output=ch;
RW=0;
EN=1;
EN=0;
//wait_lcd
delay();
return;
}