# Blink without delay and millis but with the DS1307 :)

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
*/

#include <Wire.h>

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.send(0x00);
Wire.endTransmission();

}

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);
}
}
getDateDs1307();
int time1 = second;

getDateDs1307();
int time2 = second;
if (abs(time1 - time2) > 1)

time1 is nearly always going to equal time2 - 99.99999999999999% of the time. Your if test will hardly ever be true.

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;
}
}

I hope this helps,

Ha, that works. These simple things sometime look so difficult Thank you.

Note that that only works for intervals under 60 seconds. If you want longer intervals you could calculate the time of day in seconds:

unsigned long time1 = ((hours*60L)+minutes)*60L+seconds;

This would let you time intervals up to half a day (43,200 seconds).

That's interesting, thanks for the info.

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)