Code: Select all
// Simple Real Time clock Example
//MCU : PIC16F877
//Crystal: 4Mhz
//Author: Noel A. Rios
unsigned char seconds;
unsigned char tenseconds;
unsigned char minutes;
unsigned char tenminutes;
unsigned char hours;
unsigned char tenhours;
unsigned char Read_RTC(unsigned char address)
{
unsigned char buffer;
I2C_Start(); // issue I2C start signal
I2C_Wr(0xD0); // send byte via I2C (device address + W)
while (!I2C_Is_Idle())
asm nop;
I2C_Wr(address); // send byte (data address)
while (!I2C_Is_Idle())
asm nop;
I2C_Repeated_Start(); // issue I2C signal repeated start
I2C_Wr(0xD1); // send byte (device address + R)
buffer = I2C_Rd(0u); // Read the data (NO acknowledge)
while (!I2C_Is_Idle())
asm nop; // Wait for the read cycle to finish
I2C_Stop();
Delay_ms(100);
return(buffer);
}
void main()
{
Lcd_Config(&PORTD,1,0,2,7,6,5,4);
Lcd_Init(&PORTD);
LCD_Cmd(LCD_CLEAR); // Clear display
LCD_Cmd(LCD_CURSOR_OFF); // Turn cursor off
Delay_ms(1000);
LCD_Out(1,6,"CLOCK"); // Print text to LCD, 1st row, 1st column
Delay_ms(1000);
LCD_Out(2,6,"TEST"); // Print text to LCD, 2nd row, 6th column
Delay_ms(1000);
LCD_Cmd(LCD_CLEAR); // Clear display
I2C_Init(100000);
I2C_Start(); //Initialize DS1307 RTC
I2C_Wr(0xD0); //RTC_WRITE_ADDR();
while (!I2C_Is_Idle())
asm nop;
I2C_Wr(0x00); //Adress
while (!I2C_Is_Idle())
asm nop;
I2C_Wr(0x00); //Seconds
while (!I2C_Is_Idle())
asm nop;
I2C_Wr(0x00); //minutes
while (!I2C_Is_Idle())
asm nop;
I2C_Wr(0x00); //Hours
while (!I2C_Is_Idle())
asm nop;
I2C_Stop();
Delay_ms(100);
do{
seconds=Read_RTC(0x00);
minutes=Read_RTC(0x01);
hours=Read_RTC(0x02);
tenseconds=seconds;
seconds&=0x0F;
tenseconds>>=4;
tenseconds&=0x0F;
tenminutes=minutes;
minutes&=0x0F;
tenminutes>>=4;
tenminutes&=0x0F;
tenhours=hours;
hours&=0x0F;
tenhours>>=4;
tenhours&=0x0F;
LCD_Chr(1,7,tenseconds+48);
LCD_Chr(1,8,seconds+48);
LCD_Chr(1,6,':');
LCD_Chr(1,4,tenminutes+48);
LCD_Chr(1,5,minutes+48);
LCD_Chr(1,3,':');
LCD_Chr(1,2,tenhours+48);
LCD_Chr(1,1,hours+48);
}while(1);
}