//=================================================================================================//
//                  BAT THIET BI KHI DUNG GIO DA DUOC CHINH TRUOC DO							   //
// Dung 1 nut bam de chon che do thiet lap time, chuyen sang gio roi phut va tro ve binh thuong sau//
//														moi lan thuc hien bam button			   //
// Dung Volume de tang hoac giam gio phut tuong ung voi mode ma button da chon					   //
/////////////////////////////////////////////////////////////////////////////////////////////////////
// 			Date: 19/03/2011	: 18:40										Code by: eMagic		   //
//=================================================================================================//
#include <htc.h>
#include <stdio.h>
#include "i2c.h"
#include "lcd.h"
__CONFIG(INTIO & WDTDIS & PWRTEN & MCLREN & UNPROTECT & DUNPROTECT & BORDIS & IESODIS & FCMDIS & LVPDIS);
#define _XTAL_FREQ 4000000
#define SLAVE_ADD 0x68
#define READ	1
#define WRITE	0
unsigned char 	time[7];
unsigned char 	c[14];
int				time_mode=0;
unsigned char	h_set,m_set;
//===============================All Function and procedure here========================
	void 			set_time();								//set first time for DS1307						
	void 			read_time();							//read to Pic
	void 			Display(char b[]);						//display Time for now
	void 			dis_settime_run(char HH,char MM);		//display Time for setting
	void			read_setup();							//read value from ADC and change to hour or minute
	void			port_init();							//
	void 			interrupt isr();						//
	unsigned int 	ReadADC();								//
	void 			init_all();								// first setup for all
	void			check_open_load();						//check to open load if right time set
//=======================================Main ===========================================
void main(void)
{	
	init_all();
	while(1)
	{
	read_time();
	check_open_load();
	Display(time);
	__delay_ms(100);
	__delay_ms(100);
	}
}
//=========================================end main======================================
void set_time()
{
	//Send Start condition
	i2c_start();
	//Send Slave address + WRITE command
	i2c_write((SLAVE_ADD<<1)|WRITE);
	//   ((SLAVE_ADD<<1)| WRITE) = ((0x68<<1)|0) = 0xD0
	//Send register address (register of Slave – the first register need to read data)
	i2c_write(0x00);//resister first
	i2c_write(0x00);//set second
	i2c_write(0x00);//set minute, auto register ++ (0x01)|
	i2c_write(0x10);//set hour
	i2c_write(0x07);//set day
	i2c_write(0x19);//set date
	i2c_write(0x03);//set month
	i2c_write(0x11);//set year
	i2c_stop();
}
void read_time()
{
	int i;
		//Send Start condition
	i2c_start();
	//Send Slave address + WRITE command
	i2c_write((SLAVE_ADD<<1)|WRITE);
	//   ((SLAVE_ADD<<1)| WRITE) = ((0x68<<1)|0) = 0xD0
	//Send register address (register of Slave – the first register need to read data)
	i2c_write(0x00);									//resister first
	i2c_stop();
	i2c_start();										// reset to read data form DS1307
	i2c_write((SLAVE_ADD<<1)|READ);
	for (i=0;i<6;i++)
		{
			time[i]= i2c_read(0); 						//second to time[0],...
		}
	time[6]= i2c_read(1); 								//read year and finish read
	i2c_stop();											//end read
}
void Display(char b[])
{   
	int i,j=0;
	// Luu y: ket qua doc tu RTC DS1307 la so BCD
	// Vi du: 24giay --> Ket qua doc ve la: 0x24
	// Nen phai tach chu so "2" va so "4" rieng ra de hien thi
	// tach bcd tu mang b, luu vao mang c -------------------------//
			for(i=0;i<7;i++)
					{										
					// mang c chua cac gia tri ascii, 14 bytes				
						// tach BCD, lay nibble cao 
						c[j]=b[i]/16+0x30;
						// lay nibble thap
						c[j+1]=(b[i]-(c[j]-0x30)*16)+0x30;		
						j+=2;
					}
	//--------------- hien thi tren lcd  ---------------------------//
			lcd_clear();
			lcd_puts("Thu ");
			lcd_putc(c[7]);			// thu trong tuan
			lcd_puts(", ");
			lcd_putc(c[8]);			// ngay
			lcd_putc(c[9]);
			lcd_puts("/");
			lcd_putc(c[10]);		// thang
			lcd_putc(c[11]);
			lcd_puts("/");
			lcd_putc(c[12]);		// nam
			lcd_putc(c[13]);
			//lcd_puts("\r\n"); 		// xuong hang
			lcd_gotoxy(0,1);
			
			lcd_puts("  ");
			lcd_putc(c[4]);			// gio
			lcd_putc(c[5]);
			lcd_puts(" : ");
			lcd_putc(c[2]);			// phut
			lcd_putc(c[3]);				
			lcd_puts(" : ");
			lcd_putc(c[0]);			// giay
			lcd_putc(c[1]);
}
void 	dis_settime_run(char HH,char MM)
{
	char	i,j,l,k;
		lcd_clear();
		lcd_puts("Moi ban thiet cai dat gio mo Device:");
		lcd_gotoxy(0,1);
						i=HH/10+0x30;
						j=HH%10+0x30;
						l=MM/10+0x30;
						k=MM%10+0x30;
				lcd_gotoxy(4,1);
				lcd_putc(j);
				lcd_putc(i);
				lcd_putc("/");
				lcd_putc(k);
				lcd_putc(l);
		//blink hour_set on LCD
				for(i=0;i<6;i++)__delay_ms(100);
		if(time_mode==1)
			{
				lcd_gotoxy(4,1);
				lcd_puts(" ");
				lcd_puts(" ");
				lcd_gotoxy(5,1);
				for(i=0;i<6;i++)__delay_ms(100);
			}
		//blink phut_set on LCD
		else if(time_mode==2)
			{
				lcd_gotoxy(7,1);
				lcd_puts(" ");
				lcd_puts(" ");
				lcd_gotoxy(8,1);
				for(i=0;i<6;i++)__delay_ms(100);
			}
}
void	read_setup()
{
	int temp;
	while	((time_mode==1)||(time_mode==2))			//
		{
				temp=ReadADC();
				if (time_mode==1)	h_set=temp%43;  	//moi gio ung voi tang 43 gia tri temp*24/1024
				if (time_mode==2)	m_set=(temp*10)%171 ; 	//moi phuttang tuong ung voi 17.1
				dis_settime_run(h_set,m_set);
		}
}
void	port_init()
{
	  unsigned char i=0;
	TRISE = 0b11111101;	//output portE.1
	PORTE = 0;			//first value
	//================================Set Up ADC=================================//
 	ANSEL=0xFF;			// NGO VAO ANALOG
 	ADFM=1;   			// KET QUA LAP DAY BEN PHAI 
  	VCFG1=0;  			// TAM TOAN THANG=5V
  	VCFG0=0;
  	ADCON0=0b00001111;	// Fs=Fosc/2...CHON KENH AN3...BAT ADON
  	TRISA3=1; 
  	ADRESH=0x00; 
  	ADRESL=0x00;
  	for(;i<10;i++) 
		__delay_ms(100);// cho khoi dong module ADC 
	
	//==============================end set up ADC===============================//
	//=============================Set Up EXT interrup===========================//
	INTEDG = 0;			//chon che do ngat 
	INTF = 0;			//xoa co ngat ngoai
	INTE = 1;			//cho phep ngat ngoai
	GIE = 1;			//cho phep ngat toan cuc
	//===============================end set up ext interrup=====================//
}
void interrupt isr()
{
	if(INTE && INTF){
		time_mode++;					//mode ==1 to set hour,==2 to set minute,==0 normal, no_setting
		if(time_mode==3) time_mode=0;
		read_setup();
	}
}
unsigned int ReadADC()
{
	__delay_us(5);
	GODONE = 1;
	while(GODONE);
	return (((unsigned int)ADRESH)<<8)|ADRESL;
}
void init_all()
{
	int i;
	port_init();					//IO init
	i2c_init();						//I2C init
	lcd_init();						//lcd init
	__delay_ms(150);
	set_time();						//set first time by code
	lcd_puts("Hello, ...");
	__delay_ms(150);
	lcd_puts("My name is Didital Clock");
	for (i=0;i<7;i++)
		__delay_ms(150);
}
void	check_open_load()
{
	char	temp_m,temp_h,i,j;
							//lay gia tri phut hien thoi de so sanh
							i=time[1]/16;
							j=(time[1]-i*16);
	temp_m=i*10+j;	
							//lay gia tri gio hien thoi de so sanh
							i=time[2]/16;
							j=(time[2]-i*16);
	temp_h=i*10+j;
	if((m_set==temp_m)&&(h_set==temp_h)) RE1=1;
}