Registro de la hora desde un RTC a una tarjeta SD (SOLUCIONADO)

Una consulta:

La siguiente es la forma en que se presenta el formato de hora en el monitor serial tomandola desde un reloj RTC:

void loop(){
DateTime now = RTC.now(); // Obtiene la fecha y hora del RTC
Serial.print(now.year(), DEC); // Año
Serial.print('/');
Serial.print(now.month(), DEC); // Mes
Serial.print('/');
Serial.print(now.day(), DEC); // Dia
Serial.print(' ');
Serial.print(now.hour(), DEC); // Horas
Serial.print(':');
Serial.print(now.minute(), DEC); // Minutos
Serial.print(':');
Serial.print(now.second(), DEC); // Segundos
Serial.println();
delay(1000); // La información se actualiza cada 1 seg.
}

La pregunta es:

Como se debe modificar ese formato para registrarlo en una memoria SD a través de un buffer o algo parecido?

Muchas gracias

Como te fue con esto John?

Hay que meter los datos en un string, y luego grabarlos en la SD. Combinando los códigos de ejemplo del RTC y de SD, he confeccionado el siguiente código:

#include <Wire.h>
#include "RTClib.h"
#include <SPI.h>
#include <SD.h>
RTC_DS1307 rtc;
const int chipSelect = 4;
void setup () {
  Serial.begin(9600);
#ifdef AVR
  Wire.begin();
#else
  Wire1.begin(); // Shield I2C pins connect to alt I2C bus on Arduino Due
#endif
  rtc.begin();

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    //rtc.adjust(DateTime(__DATE__, __TIME__));
  }

  Serial.print("Initializing SD card...");
  // make sure that the default chip select pin is set to
  // output, even if you don't use it:
  pinMode(10, OUTPUT);

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }
  Serial.println("card initialized.");
}
void loop () {
  String dataString = "";
  DateTime now = rtc.now();

  dataString += String(now.year(), DEC);
  dataString += "/";
  dataString += String(now.month(), DEC);
  dataString += "/";
  dataString += String(now.day(), DEC);
  dataString += " ";
  dataString += String(now.hour(), DEC);
  dataString += ":";
  dataString += String(now.minute(), DEC);
  dataString += ":";
  dataString += String(now.second(), DEC);
  dataString += " - ";
  dataString += String (analogRead(A0));
  File dataFile = SD.open("datalog.txt", FILE_WRITE);

  // if the file is available, write to it:
  if (dataFile) {
    dataFile.println(dataString);
    dataFile.close();
    // print to the serial port too:
    Serial.println(dataString);
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening datalog.txt");
  }
  delay(1000);
}

Graba cada segundo la fecha y la hora, seguido del valor del pin analógico 0. No he conectado nada a ese pin, para que se graben valores aleatorios. Este es el resultado en el archivo datalog.txt grabado en la SD:

2015/4/24 16:58:56 - 1023
2015/4/24 16:58:57 - 1000
2015/4/24 16:58:58 - 1023
2015/4/24 16:58:59 - 58
2015/4/24 16:59:0 - 0
2015/4/24 16:59:1 - 820
2015/4/24 16:59:2 - 1023
2015/4/24 16:59:3 - 507
2015/4/24 16:59:4 - 548
2015/4/24 16:59:5 - 841
2015/4/24 16:59:6 - 706
2015/4/24 16:59:7 - 629
2015/4/24 16:59:8 - 561
2015/4/24 16:59:9 - 525
2015/4/24 16:59:10 - 513
2015/4/24 16:59:11 - 512
2015/4/24 16:59:12 - 478
2015/4/24 16:59:13 - 464
2015/4/24 16:59:14 - 470
2015/4/24 16:59:15 - 494
2015/4/24 16:59:17 - 491
2015/4/24 16:59:18 - 486
2015/4/24 16:59:19 - 470
2015/4/24 16:59:20 - 463
2015/4/24 16:59:21 - 481
2015/4/24 16:59:22 - 496
2015/4/24 16:59:23 - 482
2015/4/24 16:59:24 - 467
2015/4/24 16:59:25 - 469
2015/4/24 16:59:26 - 482
2015/4/24 16:59:27 - 484
2015/4/24 16:59:28 - 472
2015/4/24 16:59:29 - 458
2015/4/24 16:59:30 - 474
2015/4/24 16:59:31 - 491
2015/4/24 16:59:32 - 480
2015/4/24 16:59:33 - 464
2015/4/24 16:59:34 - 460
2015/4/24 16:59:35 - 475
2015/4/24 16:59:36 - 473
2015/4/24 16:59:37 - 399
2015/4/24 16:59:38 - 431
2015/4/24 16:59:39 - 447

Fíjate en lo que hace el loop. Al principio del todo, vacía la variable datastring, después, adquiere los datos del RTC, los va añadiendo a la variable datastring, seguido de un guion y el valor del pin analógico 0.

Cuando tenemos todo metido en datastring, abrimos el archivo datalog.txt en modo escritura (si no existe se crea), si el archivo está disponible (debería estarlo, lo acabamos de abrir), hacemos un println del contenido de datastring en el archivo datalog.txt, cerramos el archivo y hacemos el mismo println por puerto serie, para poder ver los datos que se han guardado en la SD.

Si por alguna razón el archivo no estuviese disponible, nos mostrará un error en el terminal serie.

Después, espera un segundo, y vuelve a empezar, borrando el contenido de datastring de nuevo al principio del loop.

Mírate sobretodo la parte de código del loop. No tiene ningún secreto. Es confeccionar toda la "frase" que quieres añadir al archivo de la SD, a base de convertir las cosas en "strings" e ir añadiéndolas a un string, para posteriormente, grabarlo a la SD.

Te respondí hace un rato allí.

Pon tu código y lo pruebo.

A mi me funciona perfectamente. Creo que, tienes algún problema, o con el módulo SD (mira bien la alimentación, ya que si no lleva regulador, hay que alimentarlo a 3,3V) o con la tarjeta SD. Prueba otra tarjeta, a ver si hay algún problema de incompatibilidad con esa.

Te muestro mis resultados por puerto serie:

Reloj RTC1307 corriendo!
Tarjeta inicializada.
2015/4/26 14:52:37 - watts/m2 - p1= 0 - p2= 0 - p3= 0
2015/4/26 14:52:38 - watts/m2 - p1= 1643 - p2= 1669 - p3= 1766
2015/4/26 14:52:39 - watts/m2 - p1= 1587 - p2= 1534 - p3= 1584
2015/4/26 14:52:40 - watts/m2 - p1= 1440 - p2= 1364 - p3= 1432
2015/4/26 14:52:41 - watts/m2 - p1= 1467 - p2= 1396 - p3= 1440
2015/4/26 14:52:42 - watts/m2 - p1= 1698 - p2= 1666 - p3= 1652
2015/4/26 14:52:43 - watts/m2 - p1= 1772 - p2= 1754 - p3= 1728
2015/4/26 14:52:44 - watts/m2 - p1= 1772 - p2= 1766 - p3= 1751
2015/4/26 14:52:45 - watts/m2 - p1= 1690 - p2= 1672 - p3= 1678
2015/4/26 14:52:46 - watts/m2 - p1= 1710 - p2= 1693 - p3= 1696
2015/4/26 14:52:47 - watts/m2 - p1= 2074 - p2= 2003 - p3= 2006
2015/4/26 14:52:48 - watts/m2 - p1= 2379 - p2= 2185 - p3= 2270
2015/4/26 14:52:49 - watts/m2 - p1= 2367 - p2= 2174 - p3= 2261

Y lo grabado en la SD:

2015/4/26 14:52:37 - watts/m2 - p1= 0 - p2= 0 - p3= 0
2015/4/26 14:52:38 - watts/m2 - p1= 1643 - p2= 1669 - p3= 1766
2015/4/26 14:52:39 - watts/m2 - p1= 1587 - p2= 1534 - p3= 1584
2015/4/26 14:52:40 - watts/m2 - p1= 1440 - p2= 1364 - p3= 1432
2015/4/26 14:52:41 - watts/m2 - p1= 1467 - p2= 1396 - p3= 1440
2015/4/26 14:52:42 - watts/m2 - p1= 1698 - p2= 1666 - p3= 1652
2015/4/26 14:52:43 - watts/m2 - p1= 1772 - p2= 1754 - p3= 1728
2015/4/26 14:52:44 - watts/m2 - p1= 1772 - p2= 1766 - p3= 1751
2015/4/26 14:52:45 - watts/m2 - p1= 1690 - p2= 1672 - p3= 1678
2015/4/26 14:52:46 - watts/m2 - p1= 1710 - p2= 1693 - p3= 1696
2015/4/26 14:52:47 - watts/m2 - p1= 2074 - p2= 2003 - p3= 2006
2015/4/26 14:52:48 - watts/m2 - p1= 2379 - p2= 2185 - p3= 2270
2015/4/26 14:52:49 - watts/m2 - p1= 2367 - p2= 2174 - p3= 2261

Los valores de los sensores no son correctos, porque no tengo nada conectado a las entradas analógicas.

Si tiene las dos entradas, prueba con la de 3,3V. La de 5V, lo normal es que lleve un regulador que baje la tensión a 3,3. Alimentándolo por el pin de 3,3V, te ahorras usar ese regulador.

Me alegro de que ya te funcione. Por favor, pon el solucionado editando el primer mensaje del post, que si lo pones en otro, no se ve desde fuera :wink:

Gracias carmeloco, Estaba buscando esto mismo que jvasquez05 hace mucho, A veces no se encuentra mucha info de lo que uno quiere hacer. Les paso mi código, es un monitor de entrega de energía de un panel solar, lo veo por la web y lo registro en una sd card, y ahora con fecha y hora gracias a ustedes, gracias.

#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
#include <Wire.h>
#include "RTClib.h" //llamado de libreria DS1307

RTC_DS1307 RTC;

byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
IPAddress ip(***, ***, **, );
IPAddress gateway(
, *, ,);
IPAddress subnet(255, 255, 255, 0);
EthernetServer server(
);

// SD card
const int chipSelect = 4;

//Sensor de corriente
float amps = 0;
float maxAmps = 0;
float lastAmps = 0;

void setup() {
Serial.begin(9600);
Ethernet.begin(mac, ip, gateway, subnet);
Wire.begin();
RTC.begin();
//RTC.adjust(DateTime(DATE, TIME));
server.begin();
pinMode(10, OUTPUT);
if (!SD.begin(chipSelect)) {
return;
}
}
void loop() {
// Sensor de corriente
amps = (508 - analogRead(A0)) * 27.03 / 1023;
amps = (amps + lastAmps) / 2;
lastAmps = amps;
maxAmps = max(maxAmps, amps);

{
// Creamos el String para almacenar lo que vayamos a mandar al archivo
String dataString = "";
DateTime now = RTC.now();
//Guardamos la temperratura en un string
dataString += String(amps);
dataString += " A;";
dataString += String(maxAmps);
dataString += " A;";
dataString += String(now.year(), DEC);
dataString += "/";
dataString += String(now.month(), DEC);
dataString += "/";
dataString += String(now.day(), DEC);
dataString += " ";
dataString += " - ";
dataString += String(now.hour(), DEC);
dataString += ":";
dataString += String(now.minute(), DEC);
dataString += ":";
dataString += String(now.second(), DEC);

File dataFile = SD.open("datalog.csv", FILE_WRITE); //Abrimos el archivo datalog.csv

// Si el archivo se ha abierto correctamente
if (dataFile) {
//almacenamos el string en elarchivo
dataFile.println(dataString);
dataFile.close();
}
}
delay (1000);
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 500 OK");
client.println("Content-Type: text/html");
client.println("Refresh: 0");
client.println();
client.print("");
client.print("Energia de Panel Solar");
client.print("");
client.print("");
client.print("");
client.print("

ENERGIA CAPTADA DEL SOL.

");
client.print("

Actual: ");
client.print(amps);
client.print(" A - ");
client.print("Maxima: ");
client.println(maxAmps);
client.print(" A");
client.println("


");
break;
}
{
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
} else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1000);
client.stop();
}
}