
/**
 * @file   I2C_RTC.c
 * @author Harshad Hapani
 * @date   1 June 2019
 * @brief  An application code for I2C communication on RTC IC(MCP7940).
 * Compilation command : 1) Open terminal : cd <code directory>
 * 			 2) arm-linux-gnueabihf-gcc I2C_RTC.c -o i2c_rtc
 *        		 3) Copy executable file and paste in /home/root of SD card
 *           		 4) run throught : ./i2c_rtc
*/


#include <stdio.h>
#include <string.h>
#include <stdlib.h>	// system()
#include <unistd.h>	// sleep()
#include <fcntl.h>	// oflag like O_RDWR
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>	

char RTC_Readbyte(char address);
void RTC_Writebyte(char address, char RtcByte);

char file_I2C0_DEV[30] = "/dev/i2c-0";
int  file;

int addr_RTC = 0b01101111;		// The I2C address of the RTC MCP7940

int main()
{
	printf("I2C Interface Project!\n");

	if((file = open(file_I2C0_DEV,O_RDWR)) < 0)
	{
		perror("Failed to open the i2c bus");
		exit(1);
	}
	
	if(ioctl(file,I2C_SLAVE,addr_RTC) < 0)
	{
		printf("Failed to acquire bus access and/or talk to slave.\n");
		exit(1);
	}
	
	char hour,min,sec;
	
	RTC_Writebyte(2,3);		//Hour
	RTC_Writebyte(1,2);		//Minute
	RTC_Writebyte(0,0x81);	//Second | [7]index for Oscillator enabled=1
	RTC_Writebyte(3,0x20);	//Day | [5] Index for Oscillator and running in case of power fail

	while(1)
	{		
		hour = RTC_Readbyte(2);
		min = RTC_Readbyte(1);
		sec = RTC_Readbyte(0);


		printf("HH:MM:SS:  %d : %d : %d\n",hour,min,sec);
		//sleep(1);
	}
	return 0;	
}

char RTC_Readbyte(char address)
{
	char data;
	char buf[10] = {0};

	buf[0] = address;

	if(write(file,buf,1) != 1)
	{
		/* ERROR HANDLING: i2c transaction failed */
		printf("Failed to write to the i2c bus.\n");
	}

	// Using I2C Read
	if (read(file,buf,1) != 1) 
	{
		/* ERROR HANDLING: i2c transaction failed */
		printf("Failed to read from the i2c bus.\n");
    	} 
	else 
	{
		data = buf[0];
    	}

	//BCD To Decimal Conversion
	if(address == 0)	//remove MSB bit in case of second
	{
		data = (((data & 0x70) >> 4) * 10) + (data & 0x0F);
	}
	else
	{
		data = (((data & 0xF0) >> 4) * 10) + (data & 0x0F);
	}

	return data;

}


void RTC_Writebyte(char address, char RtcByte)
{
	char buf[10] = {0};

	buf[0] = address;
	buf[1] = RtcByte;

	if(write(file,buf,2) != 2)
	{
		/* ERROR HANDLING: i2c transaction failed */
		printf("Failed to write to the i2c bus.\n");
	}
}


