code:
#define DS1307_ID_Write 0xD0 //11010000 :000 slave address
#define DS1307_ID_Read 0xD1 //11010001 :001 slave address ,Read=1
// Arduino Pins
#define SDA 0 // i2c Serial data
#define SCL 1 // i2c Serial clock\
void i2c_start(void);
void i2c_stop(void);
void i2c_write(unsigned char output_data);
void PCF8574A_Write(unsigned char data);
void i2c_write_bit(int data_bit);
//------------------------- library I2C ----------------------
void i2c_start(void)
{
pinMode(SCL, OUTPUT);
pinMode(SDA, OUTPUT);
digitalWrite(SDA, HIGH);
digitalWrite(SCL, HIGH);
digitalWrite(SDA, LOW);
delayMicroseconds(1);
digitalWrite(SCL, LOW);
delayMicroseconds(1);
}
void i2c_acknowledge(void)
{
digitalWrite(SDA, LOW);
delayMicroseconds(1);
digitalWrite(SCL, HIGH);
delayMicroseconds(1);
digitalWrite(SCL, LOW);
delayMicroseconds(1);
digitalWrite(SDA, LOW);
delayMicroseconds(1);
}
void i2c_stop(void)
{
digitalWrite(SCL, HIGH);
delayMicroseconds(1);
digitalWrite(SDA, HIGH);
}
void i2c_write(unsigned char output_data)
{
int iBit=0;
for(int iloop = 0 ; iloop < 8 ; iloop++)
{
iBit = ((output_data & 0x80) >> 7 ) ;
digitalWrite(SDA,iBit);
delayMicroseconds(1);
digitalWrite(SCL, HIGH);
delayMicroseconds(1);
digitalWrite(SCL, LOW);
delayMicroseconds(1);
digitalWrite(SDA, LOW);
output_data = output_data << 1 ;
}
}
byte i2c_read (void)
{
byte buff_byte_input=0x00;
for(byte icount=0 ; icount<8 ; icount++)
{
pinMode(SDA, INPUT);
digitalWrite(SDA, LOW);
digitalWrite(SCL, HIGH);
buff_byte_input = buff_byte_input << 1 ;
buff_byte_input |= digitalRead(SDA);
delayMicroseconds(1);
digitalWrite(SCL, LOW);
delayMicroseconds(1);
digitalWrite(SDA, LOW);
}
//Serial.println(buff_byte_input,HEX);
return (buff_byte_input);
}
void DS1307_Write(unsigned char data)
{
i2c_start(); // |-[S]-| ;Start Condition
i2c_write(DS1307_ID_Write); // |---Slave address (PCF8574)--[A2=0,A1=0,A0=0]---| + |-R/W-|
i2c_acknowledge(); // |-[A]-| ;Active LOW
i2c_write(data); // |-------------------data to port-----------------------|
i2c_acknowledge(); // |-[A]-| ;Active LOW
i2c_stop(); // |-[P]-| ;Stop Condition
}
byte DS1307_Read(void)
{
byte ibuff;
i2c_start();
i2c_write(DS1307_ID_Read);
i2c_acknowledge();
ibuff=i2c_read();
i2c_acknowledge();
i2c_stop();
return(ibuff);
}
//-------------------end library I2C --------------------------
void setup()
{
pinMode(SCL, OUTPUT);
pinMode(SDA, OUTPUT);
digitalWrite(SDA, HIGH);
digitalWrite(SCL, HIGH);
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
}
void loop()
{
DS1307_Write(0x00);//address 0x00 |ch @ 1 bit =0| |10sec @ 3 bit | |sec @ 4 bit|
if(DS1307_Read()==0x01)
{
digitalWrite(2, LOW);
//delay(2000);
}
else digitalWrite(2, HIGH);
DS1307_Write(0x00);//address 0x05 |ch @ 1 bit =0| |10 year @ 3 bit | |year @ 4 bit|
if(DS1307_Read()==0x11)
{
digitalWrite(3, LOW);
}
else digitalWrite(3, HIGH);
}