Write a c code to interface RTC (Real Time Clock) with 8051 micro-controller

 write c code to interface RTC (Real Time Clock) with 8051 micro-controller


C code to interface RTC (Real Time Clock) with 8051 micro controller using I2C communication


#include <reg51.h>

#include <stdio.h>


#define RTC_ADDRESS 0xD0 // Address of RTC device

#define RTC_SECONDS 0x00 // Address of seconds register

#define RTC_MINUTES 0x01 // Address of minutes register

#define RTC_HOURS 0x02 // Address of hours register

#define RTC_DAY 0x03 // Address of day register

#define RTC_DATE 0x04 // Address of date register

#define RTC_MONTH 0x05 // Address of month register

#define RTC_YEAR 0x06 // Address of year register


void i2c_start();

void i2c_stop();

void i2c_write(unsigned char data);

unsigned char i2c_read();


void main()

{

    unsigned char seconds, minutes, hours, day, date, month, year;


    // Initialize I2C communication

    TMOD = 0x20;

    TH1 = 0xFD;

    SCON = 0x50;

    TR1 = 1;


    // Read current time from RTC

    i2c_start();

    i2c_write(RTC_ADDRESS);

    i2c_write(RTC_SECONDS);

    i2c_start();

    i2c_write(RTC_ADDRESS | 0x01);

    seconds = i2c_read() & 0x7F; // Clear the CH bit (clock halt bit)

    minutes = i2c_read();

    hours = i2c_read();

    day = i2c_read();

    date = i2c_read();

    month = i2c_read();

    year = i2c_read();

    i2c_stop();


    // Print current time

    printf("Current time: %02x:%02x:%02x\n", hours, minutes, seconds);

    printf("Current date: %02x/%02x/%02x\n", date, month, year);

}


// Function to generate I2C start condition

void i2c_start()

{

    SDA = 1;

    SCL = 1;

    SDA = 0;

    SCL = 0;

}


// Function to generate I2C stop condition

void i2c_stop()

{

    SDA = 0;

    SCL = 1;

    SDA = 1;

}


// Function to write data to I2C bus

void i2c_write(unsigned char data)

{

    unsigned char i;

    for(i=0;i<8;i++)

    {

        SDA = data & 0x80;

        SCL = 1;

        SCL = 0;

        data <<= 1;

    }

    SDA = 1;    SCL = 1;    SCL = 0;

}

// Function to read data from I2C bus

unsigned char i2c_read()

{

    unsigned char i, data=0;

    SDA = 1;

    for(i=0;i<8;i++)

    {        SCL = 1;

        data = (data << 1) | SDA;

        SCL = 0;

    }

    return data;

}


Note: that this code assumes that the I2C pins (SDA and SCL) are connected to P3.4 and P3.5 of the 8051 micro-controller, respectively. You may need to modify the code if your connections are different.