DS1307 Real time clock Datalogger

              if (currentTime >= lastReadTime + refresh_rate) {

You shouldn't be adding time values. That can cause problems if the values roll over. Only subtraction is guaranteed to work.

With 1500 lines of code, why do you expect to hit EVERY second on the mark? Opening and closing files takes time. Writing to files takes time.

          unsigned long currentTime = 3600*hour+60*minute+second;
              lastReadTime = 3600*hour+60*minute+second;

Between those two assignments, lots of time has ticked away.

Thank you too PaulS. I took your advices, I tried the substraction in the code and it runs a few better than before.....but I see trhat this part is uncorrect:
unsigned long currentTime = 3600hour+60minute+second;
lastReadTime = 3600hour+60minute+second;

If the day changes at 00h, this would cause a problem!! This datalogger must to run for a few days. If anyone knows any example of a datalogger that can help me to save data each predefined time, please post it!

When I finish my code completly, I would post it.....but I think that now is unnecesary, because it has a lot of menus, submenus and other parts unfinished, and it may cause problems to other users.
Thank you to everyone!!

I partially solved the problem using UNIX time, but now, the delay is being existing yet :disappointed_relieved: Anyone knows how to store the time with precission (using more variables or something like this)??? I tried a lot of methods, but the best option is the next....(I must to repeat that I don´t copy all code, because it has 1500 lines of length. But if you need it, I´ll post it. Thank you to everyone

DateTime now = RTC.now(); //Para obtener el tiempo unix
unsigned long currentTime = now.unixtime();//Obtiene el tiempo UNIX para el tiempo de refresco unicamente
if (currentTime -lastReadTime >= refresh_rate) {

File logFile = SD.open("LOG.txt", O_CREAT | O_WRITE);//O_CREAT | O_WRITE puede cambiarse por FILE_WRITE

lastReadTime = currentTime;

logFile.print(monthDay);
logFile.print("/");
logFile.print(month);
logFile.print("/");
logFile.print(year);

logFile.print(" - ");

logFile.print(hour);
logFile.print(":");
logFile.print(minute);
logFile.print(":");
logFile.print(second);

logFile.print(",");//Separador de columna

for (int l=0; l<numSensoresT; l++)
{
logFile.print(temparray[l]);
if (l < numSensoresT-1)
{
logFile.print(",");
}
else
{
logFile.println();

}
}

logFile.close();

}

Can you describe what your problem is?

Your code logs the sensor values every refresh_rate seconds. What do you expect it to do?

At first, thank you for your fast answer pylon....My problem is the precission: When I put a refresh time It takes samples good and makes a timestamp that seems good, but when it has 30-150 samples (it depends, and its aleatory-I think), the timestamp goes 1 second after, as I describe in my first post, for example if the sample rate is 30 seconds and begins in second 00: the routine is 00 30 00 30 00 [....]30 00 31. It may be a solution for this (this is an end of studies project, for the university, and I wish to do it perfect). Thank you :slight_smile:

If this is still the case even for the code above, your problem is in the main code not in the posted part of it. Meaning you have to post the full code to enable us to find the bug.

My guess is that your main loop is run only once a second. Then this kind of time slip is possible and probable after some time.

First of all....Thank you very much for your answer pylon...I´ll post the code now....But before this, I must to explain various things of my code (for best understanding):

-The first thing is that I´m relatively newbie in this kind of programming languaje, and Im sure that you will see a lot of bugs of other parts of the program.
-This project is a part of my end studies project (Naval Engineering), this instrument will log temperatures, air flows and other parameters to study the efficiency of a marine instalation (i´ll do some studies too-when I finish this instrument)
-This instrument-At the moment has programmed a Nokia 5110LCD, a keypad (for configure parameters, and configurations like number of sensors or the date or time in the DS1307 RTC, an SD card to save data, and temperature sensors DS18B20).
-The menus (and there are a lot) are incompleted, only run the things I have configured at the moment.
-the code is messy, so I order it when finished all.
-This is an example what I got in an excel:

Fecha y hora T1 T2 T3 T4 T5
21/11/12 - 5:37:3 18.12 18.31 18.50 18.19 18.19
21/11/12 - 5:52:3 18.31 18.56 18.69 18.44 18.50
21/11/12 - 6:7:3 18.19 18.50 18.62 18.44 18.37
21/11/12 - 6:22:3 18.19 18.44 18.56 18.31 18.31
21/11/12 - 6:37:3 18.12 18.31 18.50 18.31 18.25
21/11/12 - 6:52:3 18.06 18.31 18.44 18.25 18.25
21/11/12 - 7:7:3 18.00 18.25 18.44 18.19 18.19
21/11/12 - 7:22:4 18.06 18.31 18.37 18.19 18.19
21/11/12 - 7:37:4 18.00 18.25 18.31 18.12 18.12
21/11/12 - 7:52:4 18.00 18.19 18.31 18.12 18.12
21/11/12 - 8:7:4 17.94 18.19 18.31 18.12 18.06
21/11/12 - 8:22:4 17.87 18.19 18.25 18.06 18.06
21/11/12 - 8:37:5 17.94 18.12 18.25 18.06 18.06
21/11/12 - 8:52:5 17.87 18.06 18.25 18.06 18.00
21/11/12 - 9:7:5 17.87 18.12 18.19 18.00 18.00
21/11/12 - 9:22:5 17.87 18.06 18.19 18.00 17.94
21/11/12 - 9:37:5 17.81 18.06 18.19 17.94 17.94
21/11/12 - 9:52:5 17.81 18.06 18.12 18.00 17.94
21/11/12 - 10:7:5 17.81 18.00 18.12 17.94 17.94
21/11/12 - 10:22:5 17.81 18.00 18.12 17.94 17.94
21/11/12 - 10:37:5 17.75 18.00 18.12 17.94 17.87
21/11/12 - 10:52:5 17.75 18.00 18.06 17.94 17.87
21/11/12 - 11:7:6 17.75 17.94 18.06 17.94 17.87
21/11/12 - 11:22:6 17.75 17.94 18.06 17.87 17.87
21/11/12 - 11:37:6 17.69 17.94 18.06 17.87 17.87
21/11/12 - 11:52:6 17.69 17.94 18.06 17.87 17.87
21/11/12 - 12:7:6 17.69 17.94 18.00 17.87 17.81
21/11/12 - 12:22:7 17.69 17.94 18.00 17.87 17.81
21/11/12 - 12:37:7 17.69 17.87 18.00 17.81 17.81
21/11/12 - 12:52:7 17.62 17.94 18.00 17.81 17.81
21/11/12 - 13:7:7 17.69 17.87 18.00 17.81 17.81
21/11/12 - 13:22:7 17.62 17.87 18.00 17.81 17.81
21/11/12 - 13:37:7 17.37 17.56 17.62 17.44 17.44
21/11/12 - 13:52:7 17.31 17.50 17.56 17.44 17.44
21/11/12 - 14:7:7 17.50 17.75 17.87 17.69 17.69
21/11/12 - 14:22:7 17.62 17.87 18.00 17.81 17.81
21/11/12 - 14:37:7 17.62 17.87 18.00 17.81 17.81

At the next post I´ll put the code.

/Desarrollado a partir de Datalogger de la libreria SD, Keypad, LCD5110 Graph y del script de 18B20/

#include <SD.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <LCD5110_Graph.h>
#include <Keypad.h>

//--------------DS1307--------
#include "Wire.h"
#include "RTClib.h"//Para poder obtener adecuadamente UNIXtime
#define DS1307_ADDRESS 0x68
byte zero = 0x00; //workaround for issue #527

RTC_DS1307 RTC;//Va acorde a RTClib.h

unsigned long s;//Segundos reloj
unsigned long mi;//Minutos reloj
unsigned long h;//Horas reloj
unsigned long ds;//Dia semana reloj
unsigned long dm;//Dia mes reloj
unsigned long me;//Mes reloj
unsigned long a;//A?o reloj

char fechahora='0';//A-Correctos/B-Incorrectos
//------------------------------

//Keypad
const byte ROWS = 4; //cuatro filas
const byte COLS = 4; //cuatro columnas

char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {6,7,8,9};
byte colPins[COLS] = {2,3,4,5};

//Dataloger Refresh Rate
unsigned long lastReadTime=0;
unsigned long refresh_rate = 0;
unsigned long currentTime=0;
unsigned long num = 0;
unsigned long numQ = 0;//Funcion de sensores de caudal (Definicion)
unsigned long t=0;
unsigned long numSensoresQ=0;
unsigned long numSensoresT=0;

char menu='0';
char menu1='A';
char menu2='A';
char menu3='A';
char menu4='A';
char menu5='A';
char menulog='A';
int pantallazo=0;

char unidad='0';

int numero=0;

int w = 0; //Contador DS18B20

Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

//LCD
LCD5110 myGLCD(45,46,47,48,49);
extern uint8_t unican[];
extern uint8_t helice[];
extern uint8_t helice2[];
extern uint8_t helice3[];
extern uint8_t flecha[];
extern uint8_t borraflecha[];

extern uint8_t SmallFont[];

uint8_t* bm;

//Define puerto 18B20s
#define ONE_WIRE_BUS 11
#define TEMPERATURE_PRECISION 12 //resoluci?n de los sensores en bits

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

//SPI SD Card Pins
//MOSI = Pin 11
//MISO = Pin 12
//SCLK = PIN 13
int CS_pin = 43;
int pow_pin = 8;

void setup()
{

Serial.begin(9600);

Wire.begin(); //Wire---DS1307 RTC

RTC.begin();

sensors.begin();//Inicializa sensores 18B20
int numSensoresT = sensors.getDeviceCount(); // Numero de sensores
int temparray[numSensoresT]; // Array que almacena un array con el numero de sensores

//--------------------------------------------------------LCD--------------------------------------------------------------------
myGLCD.InitLCD();
myGLCD.setFont(SmallFont);

myGLCD.clrScr();
myGLCD.drawBitmap(0, 0, unican, 84, 48);
myGLCD.update();

delay(2000);

myGLCD.clrScr();
myGLCD.drawBitmap(0, 0, helice, 84, 48);
myGLCD.update();
delay(250);

myGLCD.clrScr();
myGLCD.drawBitmap(0, 0, helice2, 84, 48);
myGLCD.update();
delay(250);

myGLCD.clrScr();
myGLCD.drawBitmap(0, 0, helice3, 84, 48);
myGLCD.update();
delay(250);

//Inicializa SD

myGLCD.clrScr();
myGLCD.print("Inicializando",CENTER, 10);
myGLCD.print("Tarjeta SD",CENTER, 20);
myGLCD.update();
delay(1500);

//CS Pin Salida
pinMode(CS_pin, OUTPUT);

//SD toma tension del pin 8, por lo q es HIGH
pinMode(pow_pin, OUTPUT);
digitalWrite(pow_pin, HIGH);

//inicializa tarjeta SD
if (!SD.begin(CS_pin))
{
myGLCD.clrScr();
myGLCD.print("Fallo de SD",CENTER, 10);
myGLCD.update();
delay(1500);

}
else
{
myGLCD.clrScr();
myGLCD.print("Tarjeta SD",CENTER, 10);
myGLCD.print("lista",CENTER, 20);
myGLCD.update();
delay(1500);
}

}

unsigned long Defineletra(){
char key = kpd.getKey();
while(key != '#')
{
switch (key)
{
case NO_KEY:
break;

case 'A':
menu=key;
break;

case 'B':
menu=key;
break;

case 'C':
menu=key;
menulog='A';
pantallazo =0;
break;

delay(1000);
}
key = kpd.getKey();
}
return menu;

}

//Definicion unidades II
unsigned long Defineletra1(){
char key = kpd.getKey();
while(key != '#')
{
switch (key)
{
case NO_KEY:
break;

case 'A':
menu1=key;
break;

case 'B':
menu1=key;
break;

case 'C':
menu1=key;
break;

case '0':
menu1=key;
menu='0';
break;

delay(1000);
}
key = kpd.getKey();
}
return menu1;

}

//Definicion unidades II
unsigned long Defineletra2(){
char key = kpd.getKey();
while(key != '#')
{
switch (key)
{
case NO_KEY:
break;

case 'A':
menu2=key;
break;

case 'B':
menu2=key;
break;

case '0':
menu2=key;
menu='0';
break;

delay(1000);
}
key = kpd.getKey();
}
return menu2;

}

//Definicion unidades II
unsigned long Defineletra3(){
char key = kpd.getKey();
while(key != '#')
{
switch (key)
{
case NO_KEY:
break;

case 'A':
menu3=key;
fechahora='0'; //Para que siempre aparezca la hora en este menu
break;

case 'B':
menu3=key;
break;

case '0':
menu3=key;
menu ='A';
break;

delay(1000);
}
key = kpd.getKey();
}
return menu3;

}

//Definicion unidades II
unsigned long Defineletra4(){
char key = kpd.getKey();
while(key != '#')
{
switch (key)
{
case NO_KEY:
break;

case 'A':
menu4=key;
break;

case 'B':
menu4=key;
break;

case '0':
menu4=key;
menu ='A';
break;

delay(1000);
}
key = kpd.getKey();
}
return menu4;

}

//Definicion unidades II
unsigned long Defineletra5(){
char key = kpd.getKey();
while(key != '#')
{
switch (key)
{
case NO_KEY:
break;

case 'A':
menu5=key;
break;

case 'B':
menu5=key;
break;

case 'C':
menu5=key;
break;

case 'D':
menu5=key;
break;

delay(1000);
}
key = kpd.getKey();
}
return menu5;

}

//Definicion unidades II
unsigned long Defineletra7(){
char key = kpd.getKey();
while(key != '#')
{
switch (key)
{
case NO_KEY:
break;

case 'A':
myGLCD.drawBitmap(62, 30, borraflecha, 8, 8);//Borra flecha en B
myGLCD.drawBitmap(66, 40, borraflecha, 8, 8);//Borra flecha C
myGLCD.drawBitmap(52, 20, flecha, 8, 8);//Dibuja flecha A
myGLCD.update();

t=3600;
break;

case 'B':
myGLCD.drawBitmap(52, 20, borraflecha, 8, 8);//Borra flecha A
myGLCD.drawBitmap(66, 40, borraflecha, 8, 8);//Borra flecha C
myGLCD.drawBitmap(62, 30, flecha, 8, 8);//Dibuja flecha en B
myGLCD.update();

t=60;
break;

case 'C':
myGLCD.drawBitmap(52, 20, borraflecha, 8, 8);//Borra flecha A
myGLCD.drawBitmap(62, 30, borraflecha, 8, 8);//Borra flecha en B
myGLCD.drawBitmap(66, 40, flecha, 8, 8);//Dibuja flecha C
myGLCD.update();

t=1;
break;

delay(1000);
}
key = kpd.getKey();
}
return t;

}

//numero unidades II
unsigned long Definenumero()
{
unsigned long num = 0;
char key = kpd.getKey();

while(key != '#')
{

switch (key)
{
case NO_KEY:
break;

case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':

num = num * 10 + (key - '0');

myGLCD.printNumI(num, 0, 30);
myGLCD.update();

break;

case '*':
num = 0;

myGLCD.update();
break;
}

key = kpd.getKey();

}

return num;
}

//numero sensores de Caudal
unsigned long DefinenumeroQ()
{
unsigned long numQ = 0;
char key = kpd.getKey();

while(key != '#')
{

switch (key)
{
case NO_KEY:
break;

case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':

numQ = numQ * 10 + (key - '0');

myGLCD.printNumI(numQ, 0, 40);
myGLCD.update();

break;

case '*':
numQ = 0;

myGLCD.update();
break;
}

key = kpd.getKey();

}

return numQ;
}

//DEfine fecha y hora
unsigned long Definediasemana()
{
unsigned long ds = 0;
char key = kpd.getKey();

while(key != '#')
{

switch (key)
{
case NO_KEY:
break;

case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':

ds = ds * 10 + (key - '0');

myGLCD.printNumI(ds, 0, 40);
myGLCD.update();

break;

case '*':
ds = 0;

myGLCD.update();
break;
}

key = kpd.getKey();

}

return ds;
}

//DEfine fecha y hora
unsigned long Definediames()
{
unsigned long dm = 0;
char key = kpd.getKey();

while(key != '#')
{

switch (key)
{
case NO_KEY:
break;

case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':

dm = dm * 10 + (key - '0');

myGLCD.printNumI(dm, 0, 40);
myGLCD.update();

break;

case '*':
dm = 0;

myGLCD.update();
break;
}

key = kpd.getKey();

}

return dm;
}

//DEfine fecha y hora
unsigned long Definemes()
{
unsigned long me = 0;
char key = kpd.getKey();

while(key != '#')
{

switch (key)
{
case NO_KEY:
break;

case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':

me = me * 10 + (key - '0');

myGLCD.printNumI(me, 0, 40);
myGLCD.update();

break;

case '*':
me = 0;

myGLCD.update();
break;
}

key = kpd.getKey();

}

return me;
}

//DEfine fecha y hora
unsigned long Defineano()
{
unsigned long a = 0;
char key = kpd.getKey();

while(key != '#')
{

switch (key)
{
case NO_KEY:
break;

case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':

a = a * 10 + (key - '0');

myGLCD.printNumI(a, 0, 40);
myGLCD.update();

break;

case '*':
a = 0;

myGLCD.update();
break;
}

key = kpd.getKey();

}

return a;
}

//DEfine fecha y hora
unsigned long Definehora()
{
unsigned long h = 0;
char key = kpd.getKey();

while(key != '#')
{

switch (key)
{
case NO_KEY:
break;

case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':

h = h * 10 + (key - '0');

myGLCD.printNumI(h, 0, 40);
myGLCD.update();

break;

case '*':
h = 0;

myGLCD.update();
break;
}

key = kpd.getKey();

}

return h;
}

//DEfine fecha y hora
unsigned long Defineminutos()
{
unsigned long mi = 0;
char key = kpd.getKey();

while(key != '#')
{

switch (key)
{
case NO_KEY:
break;

case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':

mi = mi * 10 + (key - '0');

myGLCD.printNumI(mi, 0, 40);
myGLCD.update();

break;

case '*':
mi = 0;
myGLCD.update();
break;
}

key = kpd.getKey();

}

return mi;
}

//DEfine fecha y hora
unsigned long Definesegundos()
{
unsigned long s = 0;
char key = kpd.getKey();

while(key != '#')
{

switch (key)
{
case NO_KEY:
break;

case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':

s = s * 10 + (key - '0');

myGLCD.printNumI(s, 0, 40);
myGLCD.update();

break;

case '*':
s = 0;
myGLCD.update();
break;
}

key = kpd.getKey();

}

return s;
}

//Definicion unidades II
unsigned long Definefechahora(){
char key = kpd.getKey();
while(key != '#')
{
switch (key)
{
case NO_KEY:
break;

case 'A':
fechahora=key;
break;

case 'B':
fechahora=key;
break;

delay(1000);
}
key = kpd.getKey();
}
return fechahora;

}

unsigned long Definelog(){
char key = kpd.getKey();
while(key != '#')
{
switch (key)
{
case NO_KEY:
break;

case 'A':
menulog=key;
break;

case 'B':
menulog=key;
break;

case 'C':
menulog=key;
break;

case 'D':
menulog=key;
break;

case '0':
menulog=key;
menu='0';
break;

delay(1000);
}
key = kpd.getKey();
}
return menulog;

}

//-----------------------------------

void loop()
{
int numSensoresT = sensors.getDeviceCount();
float temparray[numSensoresT];

inicio:
if (menu=='0')
{
myGLCD.clrScr();
myGLCD.print("-MENU-", CENTER, 0);
myGLCD.drawLine(2,8,82,8);
myGLCD.print("#: Confirmar", CENTER, 10);
myGLCD.print("A: Config", 0, 20);
myGLCD.print("B: SD", 0, 30);
myGLCD.print("C: Datos", 0, 40);
myGLCD.update();
char menu=Defineletra();
}

else if (menu =='A')
{
myGLCD.clrScr();
myGLCD.print("CONFIGURACION", CENTER, 0);
myGLCD.drawLine(2,8,82,8);
myGLCD.print("A:Tiempo", 0, 10);
myGLCD.print("B: Sensores", 0, 20);
myGLCD.print("C: Unidades", 0, 30);
myGLCD.print("0: Volver", 0, 40);
myGLCD.update();
char menu1=Defineletra1();

if (menu1=='A')
{inicio3:
myGLCD.clrScr();
myGLCD.print("-TIEMPO-", CENTER, 0);
myGLCD.drawLine(2,8,82,8);
myGLCD.print("A:Fecha/h", 0, 10);
myGLCD.print("B: Periodo Log", 0, 20);
myGLCD.print("0: Volver", 0, 30);
myGLCD.update();
char menu3=Defineletra3();

if (menu3=='A')
{

while(fechahora=='0')
{
myGLCD.clrScr();
myGLCD.print("A:Correcto", 0, 0);
myGLCD.print("B:Cambiar", 0, 10);
verhora();

char fechahora=Definefechahora();

}

while(fechahora=='A')
{
{goto inicio3;}
}

while(fechahora=='B')
{
ponerhora();

{goto inicio3;}
}

}

else if (menu3=='B')
{

myGLCD.clrScr();
myGLCD.print("Definir unidad", 0, 0);
myGLCD.print("y pulsar #", CENTER, 10);
myGLCD.print("A: Horas", 0, 20);
myGLCD.print("B: Minutos", 0, 30);
myGLCD.print("C: Segundos", 0, 40);
myGLCD.update();
char unidad=Defineletra7();

myGLCD.clrScr();
myGLCD.print("Numero unidades", 0, 0);
myGLCD.print("#: Confirmar", 0, 10);
myGLCD.print(": Borrar", 0, 20);
myGLCD.update();
unsigned long num = Definenumero();
numero = num;
refresh_rate=(num
t);
{goto inicio3;}
}

else if (menu3=='0')
{goto inicio;}

}

else if (menu1=='B')
{ inicio4:
myGLCD.clrScr();
myGLCD.print("SENSORES", 0, 0);
myGLCD.drawLine(2,8,82,8);
myGLCD.print("A:Temperatura", 0, 10);
myGLCD.print("B: Caudal", 0, 20);
myGLCD.print("0: Volver", 0, 30);
myGLCD.update();
char menu4=Defineletra4();

if (menu4=='A')
{

myGLCD.clrScr();
myGLCD.print("Detectando", CENTER, 10);
myGLCD.print("sensores", CENTER, 20);
myGLCD.update();

delay(1000);

myGLCD.clrScr();
myGLCD.print("SENSORES:", 4, 10);
myGLCD.printNumI(numSensoresT, 58, 10);
myGLCD.update();
delay (1000);

{goto inicio4;}

}

else if (menu4=='B')
{
myGLCD.clrScr();
myGLCD.print("-CAUDAL-", CENTER, 0);
myGLCD.print("Definir numero", CENTER, 10);
myGLCD.print("de sensores", CENTER, 20);
myGLCD.print("y pulsar #", CENTER, 30);
myGLCD.update();
unsigned long numQ=DefinenumeroQ();
numSensoresQ=numQ;
{goto inicio4;}
}

else if (menu4=='0')
{goto inicio;}

}

else if (menu1=='0')
{goto inicio;}

}

else if (menu == 'B')
{inicio2:
myGLCD.clrScr();
myGLCD.print("TARJETA SD", CENTER, 0);
myGLCD.drawLine(2,8,82,8);
myGLCD.print("A:Formatear", 0, 10);
myGLCD.print("B: Extraer", 0, 20);
myGLCD.print("0: Volver", 0, 30);
myGLCD.update();
char menu2=Defineletra2();

if (menu2=='0')
{goto inicio;}

}

while (menu == 'C')
{

while (pantallazo == 0)
{

//Escritura del encabezado
File logFile = SD.open("LOG.txt", FILE_WRITE);
if (logFile)
{
logFile.println(", , , ,"); //Dejar linea en blanco, por si hay datos previos

logFile.print("Fecha y hora");
logFile.print(",");

for (int encabezado=0; encabezado<numSensoresT;encabezado++) //
{
logFile.print("T");
logFile.print(encabezado+1);

if (encabezado < numSensoresT-1)
{
logFile.print(",");
}
else
{
logFile.println();
}

}
}
else
{
myGLCD.clrScr();
myGLCD.print("Fallo de",CENTER, 10);
myGLCD.print("tarjeta",CENTER, 20);
myGLCD.print("SD",CENTER, 20);
myGLCD.update();
delay(1500);

}

logFile.close();

delay(3000);

myGLCD.clrScr();
myGLCD.print("PERIODO", 0, 0);
myGLCD.printNumI(numero, 0, 10);

if (t==3600)
{
myGLCD.print(" horas", 15, 10);
}

else if (t==60)
{
myGLCD.print("min.", 15, 10);
}

else if (t==1)
{
myGLCD.print("segs.", 15, 10);
}

else if(t==0)
{
myGLCD.print("ND", 15, 10);
}

myGLCD.drawLine(1,18,83,18);

myGLCD.print("Sensores T:", 0, 21);
myGLCD.printNumI(numSensoresT, 64, 21);

myGLCD.print("Sensores Q:", 0, 31);
myGLCD.printNumI(numSensoresQ, 64, 31);
myGLCD.update();

delay(3000);

myGLCD.clrScr();
myGLCD.print("0:STOP", 0, 0);
myGLCD.print("A: Temp 1", 0, 10);
myGLCD.print("B: Temp. 2", 0, 20);
myGLCD.print("C: Caudales 1", 0, 30);
myGLCD.print("D: Caudales 2", 0, 40);
myGLCD.update();

delay(3000);

pantallazo++;
}

sensors.requestTemperatures(); // Petici?n de temperatura a todos los sensores

for (w=0; w<numSensoresT; w++)//Para la creaci?n del array de temperaturas
{

float temp = sensors.getTempCByIndex(w); //Toma la temperatura del sensor i y la almacena en la variable temp
temparray[w] = (temp);

}

ini:

if (menulog == 'A'){

myGLCD.clrScr();

for (int j=0; j<numSensoresT;j++) //
{
int a=(10*j);

myGLCD.print("T", 0, a);
myGLCD.printNumI((j+1), 8 ,a);
myGLCD.print(":", 20, a);
myGLCD.printNumF(temparray[j], 3, 25 ,a); //El 3 se cambia segun precision requerida, Estoy usando 12 bits para el ds18b20-->0.0625?C precision
myGLCD.print("*C", 62, a);

}

myGLCD.update();

}

else if (menulog == 'B')
{

myGLCD.clrScr();

for (int k=5; k<numSensoresT;k++) //Cambiar 3 por 5 y 30 por 50 en prox fila
{
int b=((10*k)-50);

myGLCD.print("T", 0, b);
myGLCD.printNumI((k+1),8 ,b);
myGLCD.print(":", 20, b);
myGLCD.printNumF(temparray[k], 3, 25 ,b); //El 3 se cambia segun precision requerida, Estoy usando 12 bits para el ds18b20-->0.0625?C precision
myGLCD.print("*C", 62, b);

}
myGLCD.update();
}

else if (menulog == 'C')
{

myGLCD.clrScr();
myGLCD.print("Caudal 1", 0, 0);
myGLCD.update();

}

else if (menulog == 'D')
{

myGLCD.clrScr();
myGLCD.print("Caudal 2", 0, 0);
myGLCD.update();

}

else if (menulog == '0')
{

myGLCD.clrScr();
myGLCD.print("STOP", CENTER, 0);
myGLCD.print("0: MENU", 0, 10);
myGLCD.print("A/B:Temperaturas", 0, 20);
myGLCD.print("C/D:Caudales", 0, 30);
myGLCD.print("#-Confirmar", 0, 40);
myGLCD.update();
char menulog=Definelog();
}

char key = kpd.getKey();//Obtiene la pantalla de menu
if(key){
menulog=key;
{goto ini;}
}

// Reseteo de registro
Wire.beginTransmission(DS1307_ADDRESS);
Wire.write(zero);
Wire.endTransmission();

Wire.requestFrom(DS1307_ADDRESS, 7);

int second = bcdToDec(Wire.read());
int minute = bcdToDec(Wire.read());
int hour = bcdToDec(Wire.read() & 0b111111); //24 horas
int weekDay = bcdToDec(Wire.read()); //0-6 -> Domingo-sabado
int monthDay = bcdToDec(Wire.read());
int month = bcdToDec(Wire.read());
int year = bcdToDec(Wire.read());

DateTime now = RTC.now(); //Para obtener el tiempo unix
unsigned long currentTime = now.unixtime();//Obtiene el tiempo UNIX para el tiempo de refresco unicamente
if (currentTime -lastReadTime >= refresh_rate) {

File logFile = SD.open("LOG.txt", O_CREAT | O_WRITE);//O_CREAT | O_WRITE puede cambiarse por FILE_WRITE
lastReadTime = now.unixtime();

logFile.print(monthDay);
logFile.print("/");
logFile.print(month);
logFile.print("/");
logFile.print(year);

logFile.print(" - ");

logFile.print(hour);
logFile.print(":");
logFile.print(minute);
logFile.print(":");
logFile.print(second);

logFile.print(",");//Separador de columna

for (int l=0; l<numSensoresT; l++)
{
logFile.print(temparray[l]);
if (l < numSensoresT-1)
{
logFile.print(",");
}
else
{
logFile.println();

}
}

logFile.close();

}

}
}

void ponerhora(){

myGLCD.clrScr();
myGLCD.print("Dia semana", 0, 0);
myGLCD.print("(1-7)", 0, 10);
myGLCD.print("*: Borrar", 0, 20);
myGLCD.print("#: Confirmar", 0, 30);
myGLCD.update();
unsigned long ds = Definediasemana();

myGLCD.clrScr();
myGLCD.print("Dia del mes", 0, 0);
myGLCD.print("(1-31)", 0, 10);
myGLCD.print("*: Borrar", 0, 20);
myGLCD.print("#: Confirmar", 0, 30);
myGLCD.update();
unsigned long dm = Definediames();

myGLCD.clrScr();
myGLCD.print("Mes", 0, 0);
myGLCD.print("(1-12)", 0, 10);
myGLCD.print("*: Borrar", 0, 20);
myGLCD.print("#: Confirmar", 0, 30);
myGLCD.update();
unsigned long me = Definemes();

myGLCD.clrScr();
myGLCD.print("Ano", 0, 0);
myGLCD.print("(0-99)", 0, 10);
myGLCD.print("*: Borrar", 0, 20);
myGLCD.print("#: Confirmar", 0, 30);
myGLCD.update();
unsigned long a = Defineano();

myGLCD.clrScr();
myGLCD.print("Hora", 0, 0);
myGLCD.print("(0-23)", 0, 10);
myGLCD.print("*: Borrar", 0, 20);
myGLCD.print("#: Confirmar", 0, 30);
myGLCD.update();
unsigned long h = Definehora();

myGLCD.clrScr();
myGLCD.print("Minutos", 0, 0);
myGLCD.print("(0-59)", 0, 10);
myGLCD.print("*: Borrar", 0, 20);
myGLCD.print("#: Confirmar", 0, 30);
myGLCD.update();
unsigned long mi = Defineminutos();

myGLCD.clrScr();
myGLCD.print("Segundos", 0, 0);
myGLCD.print("(0-59)", 0, 10);
myGLCD.print("*: Borrar", 0, 20);
myGLCD.print("#: Confirmar", 0, 30);
myGLCD.update();
unsigned long s = Definesegundos();

byte second = s; //0-59
byte minute = mi; //0-59
byte hour = h; //0-23
byte weekDay = ds; //1-7
byte monthDay = dm; //1-31
byte month = me; //1-12
byte year = a; //0-99

Wire.beginTransmission(DS1307_ADDRESS);
Wire.write(zero); //stop Oscillator

Wire.write(decToBcd(second));
Wire.write(decToBcd(minute));
Wire.write(decToBcd(hour));
Wire.write(decToBcd(weekDay));
Wire.write(decToBcd(monthDay));
Wire.write(decToBcd(month));
Wire.write(decToBcd(year));

Wire.write(zero); //start

Wire.endTransmission();

}

byte decToBcd(byte val){

//Convierte el numero normal decimal a binario codificado.
return ( (val/10*16) + (val%10) );
}

byte bcdToDec(byte val) {
// Convert el binario codificado a decimal
return ( (val/16*10) + (val%16) );
}

void verhora(){

// Reseteo de registro
Wire.beginTransmission(DS1307_ADDRESS);
Wire.write(zero);
Wire.endTransmission();

Wire.requestFrom(DS1307_ADDRESS, 7);

int second = bcdToDec(Wire.read());
int minute = bcdToDec(Wire.read());
int hour = bcdToDec(Wire.read() & 0b111111); //24 horas
int weekDay = bcdToDec(Wire.read()); //0-6 -> Domingo-sabado
int monthDay = bcdToDec(Wire.read());
int month = bcdToDec(Wire.read());
int year = bcdToDec(Wire.read());

myGLCD.printNumI(monthDay, 0, 20);
myGLCD.print("/", 15, 20);
myGLCD.printNumI(month, 26, 20);
myGLCD.print("/", 44, 20);
myGLCD.printNumI(year, 55, 20);

myGLCD.printNumI(hour, 0, 30);
myGLCD.print(":", 15, 30);
myGLCD.printNumI(minute, 26, 30);
myGLCD.print(":", 44, 30);
myGLCD.printNumI(second, 55, 30);

myGLCD.update();

}

unsigned long currentTime = 3600*hour+60*minute+second;
              if (currentTime >= lastReadTime + refresh_rate) {

3600hour can potentially overflow: 360023 = 82K > 64k (for unsigned short).

The same with "lastReadTime + refresh_rate"

Use this instead:

unsigned long currentTime = 3600ul*hour+60*minute+second;

A far better way, if you have implemented time.h, is to use an unsigned long type to keep time.

But as I said before...there are a lot of lines of code......Anyone knows how to store the first reading UNIX time into a variable??? The only idea I have is storing it on SD, and recover it. But if I have it I can make a cycle (i++) and with this I cant do the next for saving: CurrentTime-firstReadTime>=i*refresh_rate...What do you think?

peko86:
I put 5 seconds of delay between samples and I begin to save data at 19:00:00, it continues with 19:00:05 19:00:10 19:00:15 19:00:20 19:00:25 19:00:31

You are telling the sketch when to do something but it has its own clock and you would be better off putting in a four second delay and asking it if it is ready to print the time. Something like "if last digit =0 or 5, then proceed, else go round and try again"

Thank you dhenry for your answer, but as I said before, this is a fake of my code, this may cause problems if the day changes.....I changed it for UNIXtime, which solves both problems (overflow and this error).

NickPyner: This is a good idea, but if the refresh rate is 1,2,3 seconds or 7...? But this could be a good option if I can't solve it by other way.

Thank you to both :slight_smile:

Your rtc will not return a 32-bit time. The only rtc that I know of that will do this is from st.

So regardless of how you keep time (via a 32-bit type or via struct time), you have to perform a conversion. That means you have to deal with promotion and issues surrounding that.