I want to use a DS1307 RTC in a home automation project to do certain time based things. I have a small DS1307 board and have managed to make it work with various sketches that I’ve found online. This code was very handy → RTC1307 - Real Time Clock - Combustory
Now I thought lets try to make a sketch like the blink without delay example but using the data from the DS1307.
But I’m getting nowhere, I don’t really have a clue how I should make this sketch… Anyone that can help me?
I’ve made the following sketch, which does not work.
/*
Blink without delay using a DS1307
Led blinks once every second.
*/
#include <Wire.h>
const int DS1307_I2C_ADDRESS = 0x68;
const int led = 13; // the number of the light pin
int ledState = LOW;
byte second, minute, hour;
// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
return ( (val/16*10) + (val%16) );
}
void getDateDs1307()
{
// Reset the register pointer
Wire.beginTransmission(DS1307_I2C_ADDRESS);
Wire.send(0x00);
Wire.endTransmission();
Wire.requestFrom(DS1307_I2C_ADDRESS, 3);
second = bcdToDec(Wire.receive() & 0x7f);
minute = bcdToDec(Wire.receive());
hour = bcdToDec(Wire.receive() & 0x3f);
}
void setup() {
Wire.begin();
pinMode(led, OUTPUT);
}
void loop(){
getDateDs1307();
int time1 = second;
getDateDs1307();
int time2 = second;
if (abs(time1 - time2) > 1)
{
if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
// set the LED with the ledState of the variable:
digitalWrite(led, ledState);
}
}
I'm not sure I understand the point, but your code might work better like this:
...
int lastTime = -1;
void loop(){
getDateDs1307();
int time1 = second;
if (abs(time1 - lastTime) > 1)
{
if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
// set the LED with the ledState of the variable:
digitalWrite(led, ledState);
lastTime = time1;
}
}
Bajdi:
Ha, that works. These simple things sometime look so difficult :roll_eyes: Thank you.
No problem. One more suggestion for next time: If all you're trying to do is switch ledState from HIGH to LOW, you can do something like this:
ledState = !ledState;
I know you were using the example code, I just thought I'd share a simpler way (less typing too ;-) )
(the example code structure of the if/else statement works better in many real world cases where, for example, you might want to do something - like controlling a pump - as well as toggling the LED's on and off)
This thread is a treasure trove of an example how to do something of an action with DS1307 other than set a clock, which is the echo-chamber Internet is full of. You guys got me to the square two! Square three will be to have DS1307 control a one of the servos at a set time intervals.