Problema con lectura en tarjeta SD que incluye fecha [Solucionado]

Hola, buenos días estoy desarrollando un proyecto el cual me va a medir tres variables cada hora, las tres lecturas se van a almacenar en una micro SD en la cual se va a incluir la fecha y hora en que se hace la lectura mediante circuito RTC (la parte electrónica me funciona correctamente) luego solicitaré por bluetooth (por ahora simulado con serial) los valores medidos en una fecha específica, el programa se encargará de buscar dentro de la SD dicha fecha y enviará los valores de vuelta. Por ahora me funciona el poder enviar todos los datos porque esa parte, como saben es sencilla, he leído en diferentes foros y páginas sobre las lecturas linea a linea entre ellos:

http://www.extremadura-web.es/Blog/2013/01/16/leer-linea-fichero-sd-en-arduino/
http://forum.arduino.cc/index.php?topic=291243.0
http://forum.arduino.cc/index.php?topic=303081.0

De ahí me he guiado para llevar el siguiente código:

#include <SD.h>
#include <Wire.h>
#include <Time.h>
#include <DS1307RTC.h>

    String sensor1;
    String sensor2;
    String sensor3;
    String hora;
    String dia;
    String mes;
    String anio;
    
byte lectura;    
unsigned long cursor;
char Ruta[9] = {'t', 'e', 's', 't', '.', 't', 'x', 't', '\0'};

int fila;    
tmElements_t tm;
int cero=0; 


const int analogInPin = A0; 
const int analog1InPin = A1;
const int analog2InPin = A2;
//valores leidos desde los sensores
int sensorValue = 0;
int sensor1Value = 0;
int sensor2Value = 0;
//string para contener los datos de entrada por serial
String inputString = "";
//cuando el string esté completo o lleno
boolean stringComplete = false; 

void setup() {
  // iniciar la comunicacion con el puerto serial a 9600 bps:
  Serial.begin(9600);
  // reserva 200 bytes para la variable inputString:
  inputString.reserve(200);
  Serial.print("Iniciando tarjeta SD...");
  // en la Ethernet Shield, CS es el pin 4. Es puesto como salida por defecto.
  // (el pin 10 en las tarhetas Arduino, 53 en la Mega) debe ser definida como salida 
  // o la libreria SD no funcionará. 
   pinMode(10, OUTPUT);
 
  if (!SD.begin(10)) {
    Serial.println("Inicio fallido");
    return;
  }
  Serial.println("Inicio hecho.");
  
    
}



void loop() {
    
  // print the results to the serial monitor:
  // print the string when a newline arrives:
  if (stringComplete) {
    
    //esta parte solo me calculará la linea final sabiendo que cada línea almacenada en la SD
    //contiene 31 caracteres incluyendo \n
    File myFile;
    myFile = SD.open("test.txt");
    if (myFile) {
      while (myFile.available()){
        lectura=myFile.read();
        cursor=myFile.position();
        }
      lectura=0;  
      fila=cursor/31;
      Serial.println(fila);
      myFile.close();
    }else {
      Serial.println("error al abrir test.txt");
    }
    
    myFile.close();

    //acá sabremos que día, mes y año se solicita teniendo en cuenta un orden para
    //el string de entrada serial algo asi como 19032015# dia,mes,anio
    String diab=inputString.substring(0,2);
    String mesb=inputString.substring(2,4);
    String aniob=inputString.substring(4,8);
    Serial.println(diab);
    Serial.println(mesb);
    Serial.println(aniob);
    
    //Por ahora sólo intenté leer una fila para saber si me clasificaba correctamente los datos
    //almacenados luego agregaré el for

    //for (int i=0;i<=fila;i++)
    
    String Lin = ReadFile(10,Ruta);
    Serial.println(Lin);
    sensor1 = Lin.substring( 0,2);
    Serial.print("sensor1:");
    Serial.println(sensor1);
   int dcPos = Lin.indexOf( "," );
   sensor2 = Lin.substring( dcPos+1,dcPos+3 );
   Serial.print("sensor2:");
    Serial.println(sensor2);
   int dPos = Lin.indexOf( "." );
   sensor3 = Lin.substring( dPos+1,dPos+3 );
   Serial.print("sensor3:");
    Serial.println(sensor3);
   int cPos = Lin.indexOf( "-" );
   hora = Lin.substring( cPos+1,cPos+9 );
   Serial.print("hora:");
    Serial.println(hora);
   int Pos = Lin.indexOf( "+" );
   dia = Lin.substring( Pos+1,Pos+3 );
   Serial.print("dia:");
    Serial.println(dia);
   int mPos = Lin.indexOf( "/" );
   mes = Lin.substring( mPos+1,mPos+3 );
   Serial.print("mes:");
    Serial.println(mes);
   int aPos = Lin.indexOf( ";" );
   anio = Lin.substring( aPos+1,aPos+5 );
   Serial.print("año:");
    Serial.println(anio);
  
    
    sensor1 = "";
    sensor2 = "";
    sensor3 = "";
    hora = "";
    dia = "";
    mes = "";
    anio = "";
  inputString = "";
  stringComplete = false;
  
}
}

/*
  SerialEvent occurs whenever a new data comes in the
 hardware serial RX.  This routine is run between each
 time loop() runs, so using delay inside loop can delay
 response.  Multiple bytes of data may be available.
 */
void serialEvent() {
  while (Serial.available()) {
    
    // get the new byte:
    char inChar = (char)Serial.read(); 
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '#') {
      stringComplete = true;
    }
    
  }
}
 
String ReadFile(int Linea,char Ruta[]){
int Lin=0;
String Resultado;
File myFile2;
byte Bin;
myFile2 = SD.open(Ruta);;
if (myFile2) {
while (myFile2.available()) {
Bin=myFile2.read();
if (Bin==13){Lin++;myFile2.read();}
else
{
if (Lin==Linea){Resultado=Resultado+(char(Bin));}
if (Lin>Linea){myFile2.close();return Resultado;}
}
}
myFile2.close();return Resultado;
}
}

Si, hay muchas variables que me sobran pero las necesito en otras partes del código, que si alguien necesita subiré luego para sus proyectos, tener en cuenta que las lineas almacenadas en la SD son así: FF,FF.FF-16:42:45+20/03;2015# (los primeros tres valores son hexadecimales como habrán notado)
Cuando pruebo únicamente la parte de leer una línea sin calcular la cantidad de filas si me devuelve los valores de cada sensor y las fechas de forma correcta, pero cuando agrego la primera parte para calcular la fecha solicitada del string me arroja valores vacíos, no entiendo el motivo, si ven algún error por favor podrían decírmelo, de antemano muchas gracias por su tiempo para leer el post y responder. Adjunto una imagen (fig1) de lo que me arroja por puerto serial. cuando invierto el orden si me da el resultado como espero (fig2), pero no puedo dejarlo así porque antes necesito primero saber que fecha se me solicita, esto es lo extraño y no encuentro explicación del por qué el orden me altera los resultados, muchas gracias de nuevo por cualquier aporte que puedan hacerme.

fig1.png

fig2.png

Buenas noches sigo trabajando en mi proyecto y aún no soluciono el problema, en estos momentos si me permite buscar datos guardados en la SD de acuerdo a la fecha que se solicita, para ello se envía un string con el día, la fecha, el año que se requiere y finalizando con numeral (ej: 20032015#), para que me funcione he debido correr a parte un código que me calcula el número de filas que tiene la SD

Archivo = SD.open("test.txt");
    if (Archivo) {
      while (Archivo.available()){
        lectura=Archivo.read();
        cursor=Archivo.position();
        }
      lectura=0;  
      fila=cursor/31;
      Archivo.close();
      delay(2000);
    }else {
      Serial.println("error al abrir test.txt");
    }
    
     Serial.println(fila);

luego en un código por separado pongo el valor del número de filas calculado y me deja buscar sin problemas la fecha específica:

#include <SD.h>
#include <Wire.h>
#include <Time.h>
#include <DS1307RTC.h>

    String sensor1;
    String sensor2;
    String sensor3;
    String hora;
    String dia;
    String mes;
    String anio;
    String ceros="00";
    
byte lectura;    
unsigned long cursor;
char Ruta[9] = {'t', 'e', 's', 't', '.', 't', 'x', 't', '\0'};

int fila;    


//string para contener los datos
String inputString = "";
//cuando el string esté completo o lleno
boolean stringComplete = false;  // whether the string is complete

void setup() {
  // iniciar la comunicacion con el puerto serial a 9600 bps:
  Serial.begin(9600);
  // reserva 200 bytes para la variable inputString:
  inputString.reserve(200);
  Serial.print("Iniciando tarjeta SD...");
  // en la Ethernet Shield, CS es el pin 4. Es puesto como salida por defecto.
  // (el pin 10 en las tarhetas Arduino, 53 en la Mega) debe ser definida como salida 
  // o la libreria SD no funcionará. 
   pinMode(10, OUTPUT);
 
  if (!SD.begin(10)) {
    Serial.println("Inicio fallido");
    return;
  }
  Serial.println("Inicio hecho.");
  
    
}



void loop() {
    
  // print the results to the serial monitor:
  // print the string when a newline arrives:
  if (stringComplete) {
    
    
             
    String diab=inputString.substring(0,2);
    String mesb=inputString.substring(2,4);
    String aniob=inputString.substring(4,8);
    Serial.println(diab);
    Serial.println(mesb);
    Serial.println(aniob);
     
    for (int i=0;i<=40;i++){
    
    String Lin = ReadFile(i,Ruta);
    //Serial.print("linea:");
    //Serial.println(Lin);
    sensor1 = Lin.substring( 0,2);
    //Serial.print("sensor1:");
    //Serial.println(sensor1);
   int dcPos = Lin.indexOf( "," );
   sensor2 = Lin.substring( dcPos+1,dcPos+3 );
   //Serial.print("sensor2:");
   //Serial.println(sensor2);
   int dPos = Lin.indexOf( "." );
   sensor3 = Lin.substring( dPos+1,dPos+3 );
   //Serial.print("sensor3:");
    //Serial.println(sensor3);
   int cPos = Lin.indexOf( "-" );
   hora = Lin.substring( cPos+1,cPos+9 );
   //Serial.print("hora:");
    //Serial.println(hora);
   int Pos = Lin.indexOf( "+" );
   dia = Lin.substring( Pos+1,Pos+3 );
   //Serial.print("dia:");
   //Serial.println(dia);
   int mPos = Lin.indexOf( "/" );
   mes = Lin.substring( mPos+1,mPos+3 );
   //Serial.print("mes:");
   //Serial.println(mes);
   int aPos = Lin.indexOf( ";" );
   anio = Lin.substring( aPos+1,aPos+5 );
   //Serial.print("año:");
   //Serial.println(anio);
    
    if (diab==dia){
      if (mesb==mes){
        if(aniob==anio){
          Serial.println(Lin);  
        }
      }
    }else{ if (diab==ceros){
            if (mesb==mes){
              if(aniob==anio){
              Serial.println(Lin);  
        }
      }  
          }
        }
        
    }     
    

  
    
    sensor1 = "";
    sensor2 = "";
    sensor3 = "";
    hora = "";
    dia = "";
    mes = "";
    anio = "";
    diab = "";
    mesb = "";
    aniob = ""; 
  
  inputString = "";
  stringComplete = false;
}

}

/*
  SerialEvent occurs whenever a new data comes in the
 hardware serial RX.  This routine is run between each
 time loop() runs, so using delay inside loop can delay
 response.  Multiple bytes of data may be available.
 */
void serialEvent() {
  while (Serial.available()) {
    
    // get the new byte:
    char inChar = (char)Serial.read(); 
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '#') {
      stringComplete = true;
    }
    
  }
}
 
String ReadFile(int Linea,char Ruta[]){
int Lin=0;
String Resultado;
File myFile2;
byte Bin;
myFile2 = SD.open(Ruta);;
if (myFile2) {
while (myFile2.available()) {
Bin=myFile2.read();
if (Bin==13){Lin++;myFile2.read();}
else
{
if (Lin==Linea){Resultado=Resultado+(char(Bin));}
if (Lin>Linea){myFile2.close();return Resultado;}
}
}
myFile2.close();return Resultado;
}
}

No entiendo por qué al querer combinar los dos códigos en uno sólo no me funciona, un compañero me comentaba que podría ser por el pin CS que se requiere de un tiempo para cambiar de maestro a esclavo, intenté separar los códigos con un delay pero aún así no me funciona, si alguien ha trabajado con memorias SD o ha tenido problemas similares o que me pueda ayudar con algo de verdad se lo agradecería mucho, de nuevo gracias por el tiempo que les tomó leer el post.

PD: adjunto el resultado del código como me funciona ahora.

fig3.png

fig4.png

Saludos
Puedes colocar los enlaces para descargar la librerias que usas para poder simularla?

Seguro te funciona asi? estas usando el shield ethernet? u otro shield?

Saludos, de esta pagina me he guiado para realizar la parte del circuito RTC y de ahí tomé las librerias time.h y DS1307RTC.h el siguiente código es el que uso para grabar los datos en la SD, esperaba que cuando me funcionara lectura podría combinarlos.

http://growino.com/rtc-ds1307-arduino/

si me funciona así pero como te digo los códigos por separado, el circuito que uso para la microSD se basa en conectarlo por medio de un divisor de tensión hecho con resistencias como se ve en la imagen y me ha funcionado

#include <SD.h>
#include <Wire.h>
#include <Time.h>
#include <DS1307RTC.h>

tmElements_t tm;
int cero=0; 
File myFile;

const int analogInPin = A0; 
const int analog1InPin = A1;
const int analog2InPin = A2;
//valores leidos desde los sensores
int sensorValue = 0;
int sensor1Value = 0;
int sensor2Value = 0;
//string para contener los datos
String inputString = "";
//cuando el string esté completo o lleno
boolean stringComplete = false;  // whether the string is complete

void setup() {
  // iniciar la comunicacion con el puerto serial a 9600 bps:
  Serial.begin(9600);
  // reserva 200 bytes para la variable inputString:
  inputString.reserve(200);
  Serial.print("Iniciando tarjeta SD...");
  // en la Ethernet Shield, CS es el pin 4. Es puesto como salida por defecto.
  // (el pin 10 en las tarhetas Arduino, 53 en la Mega) debe ser definida como salida 
  // o la libreria SD no funcionará. 
   pinMode(10, OUTPUT);
 
  if (!SD.begin(10)) {
    Serial.println("Inicio fallido");
    return;
  }
  Serial.println("Inicio hecho.");
  
}

void loop() {
  // lectura de valores analogos y cambio de rango (de 0-1023 a 0-255)
  sensorValue = analogRead(analogInPin)/4;
  sensor1Value= analogRead(analog1InPin)/4;
  sensor2Value= analogRead(analog2InPin)/4;
  myFile = SD.open("test.txt", FILE_WRITE);
 
  // si el archivo se abre correctamente escribimos:
  if (myFile) {
    Serial.print("escribiendo en test.txt...");
    print2digits2(sensorValue);
    myFile.print(",");
    print2digits2(sensor1Value);
    myFile.print(".");
    print2digits2(sensor2Value);
    myFile.print("-");
    if (RTC.read(tm)) {
      print2digits(tm.Hour);
      myFile.print(":");
      print2digits(tm.Minute);
      myFile.print(":");
      print2digits(tm.Second);
      myFile.print("+");
      print2digits(tm.Day);
      myFile.print('/');
      print2digits(tm.Month);
      myFile.print(';');
      myFile.print(tmYearToCalendar(tm.Year));
      myFile.println('#');
    // close the file:
    myFile.close();
    Serial.println("Hecho.");
    }else {
    if (RTC.chipPresent()) {
      Serial.println("The DS1307 is stopped.  Please run the SetTime");
      Serial.println("example to initialize the time and begin running.");
      Serial.println();
    } else {
      Serial.println("DS1307 read error!  Please check the circuitry.");
      Serial.println();
    }
    delay(9000);
    }
  } else {
    // si el archivo no se puede abrir, escribimos error:
    Serial.println("error al abrir test.txt");
  }
    delay(20000);
    
  // print the results to the serial monitor:
  // print the string when a newline arrives:
  if (stringComplete) {
    
    if (inputString=="cmdreadtodo#"){
    // abriendo el archivo para leer:
  myFile = SD.open("test.txt");
  // Si se abre correctamente
  if (myFile) {
    Serial.println("test.txt:");
 
    // leemos el archivo hasta que ya no haya mas en el y lo enviamos por el puerto serie:
    while (myFile.available()) {
    	Serial.write(myFile.read());
    }
    // cerramos el archivo:
    myFile.close();
    } else {
  	// si no se puede abrir el archivo, enviamso un error:
    Serial.println("error al abrir test.txt");
  }
  inputString = "";
    stringComplete = false;
    }
 inputString = "";
 stringComplete = false; 
}
}

/*
  SerialEvent occurs whenever a new data comes in the
 hardware serial RX.  This routine is run between each
 time loop() runs, so using delay inside loop can delay
 response.  Multiple bytes of data may be available.
 */
void serialEvent() {
  while (Serial.available()) {
    
    // get the new byte:
    char inChar = (char)Serial.read(); 
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '#') {
      stringComplete = true;
    }
    
  }
}
 
void print2digits(int number) {
  if (number >= 0 && number < 10) {
    myFile.print(cero);
   }
  myFile.print(number);
}

void print2digits2(int number) {
  if (number >= 0 && number < 15) {
    myFile.print(cero);
   }
  myFile.print(number, HEX);
}

Ok, Aun estoy viendo como hacer funcionar tu busqueda.

Pero he hecho unas modificaciones en los codigos que podrias probar.
Los delays no deben ser tan altos como 20000, eso es muy perjudicial.

#include <SD.h>
#include <Wire.h>
#include <Time.h>
#include <DS1307RTC.h>
#include <SPI.h>

tmElements_t tm;
int cero=0; 
File myFile;

#define analogInPin     A0 
#define analog1InPin    A1
#define analog2InPin    A2
//valores leidos desde los sensores
int sensorValue = 0;
int sensor1Value = 0;
int sensor2Value = 0;
//string para contener los datos
String inputString = "";
//cuando el string esté completo o lleno
boolean stringComplete = false;  // whether the string is complete



void grabar(){
    sensorValue = analogRead(analogInPin)/4;
    sensor1Value= analogRead(analog1InPin)/4;
    sensor2Value= analogRead(analog2InPin)/4;
    myFile = SD.open("test.txt", FILE_WRITE);
   
    // si el archivo se abre correctamente escribimos:
    if (myFile) {
      Serial.print("escribiendo en test.txt...");
      print2digits2(sensorValue);
      myFile.print(",");
      print2digits2(sensor1Value);
      myFile.print(".");
      print2digits2(sensor2Value);
      myFile.print("-");
      if (RTC.read(tm)) {
        print2digits(tm.Hour);
        myFile.print(":");
        print2digits(tm.Minute);
        myFile.print(":");
        print2digits(tm.Second);
        myFile.print("+");
        print2digits(tm.Day);
        myFile.print('/');
        print2digits(tm.Month);
        myFile.print('/');
        myFile.print(tmYearToCalendar(tm.Year));
        myFile.println('#');
        // close the file:
        myFile.close();
        Serial.println("Hecho.");
      } else {
        if (RTC.chipPresent()) {
          Serial.println("The DS1307 is stopped.  Please run the SetTime");
          Serial.println("example to initialize the time and begin running.");
          Serial.println();
        } else {
          Serial.println("DS1307 read error!  Please check the circuitry.");
          Serial.println();
        }
      }
    } else {
      // si el archivo no se puede abrir, escribimos error:
      Serial.println("error al abrir test.txt");
    }
}
void setup() {
  // iniciar la comunicacion con el puerto serial a 9600 bps:
  Serial.begin(9600);
  // reserva 200 bytes para la variable inputString:
  inputString.reserve(200);
  Serial.print("Iniciando tarjeta SD...");
  // en la Ethernet Shield, CS es el pin 4. Es puesto como salida por defecto.
  // (el pin 10 en las tarhetas Arduino, 53 en la Mega) debe ser definida como salida 
  // o la libreria SD no funcionará. 
   pinMode(10, OUTPUT);
 
  if (!SD.begin(4)) {
    Serial.println("Inicio fallido");
    return;
  }
  Serial.println("Inicio hecho.");
  
}

unsigned long tiempo = millis();

void loop() {
  // lectura de valores analogos y cambio de rango (de 0-1023 a 0-255)
  if((millis()-tiempo)/1000 >= 20){
    grabar();
    tiempo = millis();
  }
  
  if (stringComplete) {
    if (inputString=="cmdreadtodo#"){
      myFile = SD.open("test.txt");
      if (myFile) {
        Serial.println("test.txt:");
        while (myFile.available()) {
    	    Serial.write(myFile.read());
          myFile.close();
        } 
      } 
      else Serial.println("error al abrir test.txt");
    }
    inputString = "";
    stringComplete = false; 
  }
}

/*
  SerialEvent occurs whenever a new data comes in the
 hardware serial RX.  This routine is run between each
 time loop() runs, so using delay inside loop can delay
 response.  Multiple bytes of data may be available.
 */
void serialEvent() {
  while (Serial.available()) {
    
    // get the new byte:
    char inChar = (char)Serial.read(); 
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '#') {
      stringComplete = true;
    }
    
  }
}
 
void print2digits(int number) {
  if (number >= 0 && number < 10) {
    myFile.print(cero);
   }
  myFile.print(number);
}

void print2digits2(int number) {
  if (number >= 0 && number < 15) {
    myFile.print(cero);
   }
  myFile.print(number, HEX);
}

También hay otras formas de ver cuantas lineas hay en el archivo.

      while (myFile.available()){
        lectura=myFile.read();
        if(lectura=='\n')fila++;
      }

Listo, muchas gracias voy a probar las modificaciones que me envías.

buenas noches, muchas gracias por las recomendaciones, ya corregí los dos códigos como me dijiste y funcionan, lo que sigue sin funcionarme es combinarlos cuando pongo las lineas para hallar la cantidad de filas y la lectura de los datos depende a la fecha de ingreso, si quito las lineas que me calculan el número de filas, la búsqueda por fecha me funciona pero debo ingresar manualmente el número máximo de filas.
De nuevo muchas gracias por tu valiosa colaboración

Bueno,
Me puse a jugar con tu codigo y lo hice con otra libreria. RTClib

Este es el codigo resultante.

#include <SD.h>
#include <Wire.h>
#include <SPI.h>
#include <RTClib.h>

RTC_DS1307 rtc;

File myFile;

#define analogInPin     A0 
#define analog1InPin    A1
#define analog2InPin    A2
//valores leidos desde los sensores
int sensorValue = 0;
int sensor1Value = 0;
int sensor2Value = 0;
//string para contener los datos
String inputString = "";
//cuando el string esté completo o lleno
boolean stringComplete = false;  // whether the string is complete

void showDate(String txt, const DateTime& dt) {
    Serial.print(F("Linea\t"); Serial.print(txt);
    Serial.print(F(' '));
    Serial.print(dt.year(), DEC);
    Serial.print(F('/'));
    Serial.print(dt.month(), DEC);
    Serial.print(F('/'));
    Serial.print(dt.day(), DEC);
    Serial.print(F(' '));
    Serial.print(dt.hour(), DEC);
    Serial.print(F(':'));
    Serial.print(dt.minute(), DEC);
    Serial.print(F(':'));
    Serial.println(dt.second(), DEC);
}



void leer_linea(){
  int sensor1;
  int sensor2;
  int sensor3;
  int cuenta = 0;
  unsigned long date;
    if(inputString.length()<8){
      Serial.println(F("Formato Fecha Incorrecto."));
      return; 
    }
    for(int i = 0; i < 8; i++){
      if(!isDigit(inputString.charAt(i))){ 
        Serial.println(F("Formato Fecha Incorrecto."));
        return;
      }
    }

    String diab=inputString.substring(0,2);
    String mesb=inputString.substring(2,4);
    String aniob=inputString.substring(4,8);

    byte uno   = diab.toInt();
    byte dos   = mesb.toInt();
    long tres  = aniob.toInt();

    DateTime dt0 (tres, dos, uno, 0, 0, 0);
    DateTime dt1 (dt0.unixtime() + 86400L); // One day later.

       
    myFile = SD.open("datal.txt");
    if (myFile) {
      while (myFile.available()){
        date = myFile.parseInt();
        sensor1 = myFile.parseInt();
        sensor2 = myFile.parseInt();
        sensor3 = myFile.parseInt();
        cuenta++;
        if(date>= dt0.unixtime() && date < dt1.unixtime()){
          showDate(String(cuenta),date);
          Serial.print("Sensor 1:\t"); Serial.println(sensor1);
          Serial.print("Sensor 2:\t"); Serial.println(sensor2);
          Serial.print("Sensor 3:\t"); Serial.println(sensor3);
        }
      }
    }else {
      Serial.println(F("error al abrir datal.txt"));
    }

    myFile.close();
    

}


void grabar(){
    sensorValue = analogRead(analogInPin)/4;
    sensor1Value= analogRead(analog1InPin)/4;
    sensor2Value= analogRead(analog2InPin)/4;
    myFile = SD.open("datal.txt", FILE_WRITE);
    // si el archivo se abre correctamente escribimos:
    if (myFile) {
      DateTime now = rtc.now();

      Serial.print("escribiendo en datal.txt...");
      //Serial.println(now.unixtime());
      myFile.print(now.unixtime());
      myFile.print(",");
      myFile.print(sensorValue);
      myFile.print(",");
      myFile.print(sensor1Value);
      myFile.print(",");
      myFile.println(sensor2Value);
      myFile.print("#");
      myFile.close();
      Serial.println("Hecho.");
    } else {
      Serial.println("error al abrir datal.txt.txt");
    }
}

void setup() {
  Serial.begin(9600);
  rtc.begin();
  Wire.begin();
  inputString.reserve(200);
  Serial.print("Iniciando tarjeta SD...");
  pinMode(10, OUTPUT);
  if (!SD.begin(4)) {
    Serial.println("Inicio fallido");
    return;
  }
  Serial.println("Inicio hecho.");
  grabar();
}

unsigned long tiempo = millis();

void loop() {
  if((millis()-tiempo)/1000 >= 20){
    grabar();
    tiempo = millis();
  }
  
  if (stringComplete) {
    leer_linea();
    inputString = "";
    stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read(); 
    inputString += inChar;
    if (inChar == '#') {
      stringComplete = true;
    }    
  }
}

Las modificaciones que realice son:
Primero se guarda la fecha en formato unixtime(), luego los valores de los tres sensores. Separadas por coma. Esto para poder usar ParseInt.

Para solicitar los datos por fecha se ingresa el dia solicitado de la siguiente manera: ddmmaaaa# (Ej. 02042015#). Envia por Serial:

Linea	1 2015/4/1 23:55:25

Sensor 1:	255

Sensor 2:	255

Sensor 3:	174

Linea	2 2015/4/1 23:55:28

Sensor 1:	255

Sensor 2:	255

Sensor 3:	183

Linea	3 2015/4/1 23:55:48

Sensor 1:	255

Sensor 2:	255

Sensor 3:	174

Donde indica la linea el año, mes, dia y hora de grabado de los datos.

buenas tardes, agradezco mucho el tiempo que te has tomado para ayudarme, intenté probar el código que me envías, ya descargué la librería que dijiste, al compilarlo me sale este error:

todo.ino: In function 'void showDate(String, DateTime)':
todo:25: error: initializer fails to determine size of '__c'
todo:27: error: initializer fails to determine size of '__c'
todo:29: error: initializer fails to determine size of '__c'
todo:31: error: initializer fails to determine size of '__c'
todo:33: error: initializer fails to determine size of '__c'
todo:35: error: initializer fails to determine size of '__c'

no le he modificado nada al código que me envías, sólo quería compilarlo.

Luego modifiqué el código en el void showDate y lo he dejado como sale en el ejemplo de la librería tal vez el string F que almacenabas los símbolos era el que me causaba problema, lo dejé así:

void showDate(String txt, const DateTime& dt) {
    Serial.print("Linea\t"); Serial.print(txt);
    Serial.print(' ');
    Serial.print(dt.year(), DEC);
    Serial.print('/');
    Serial.print(dt.month(), DEC);
    Serial.print('/');
    Serial.print(dt.day(), DEC);
    Serial.print(' ');
    Serial.print(dt.hour(), DEC);
    Serial.print(':');
    Serial.print(dt.minute(), DEC);
    Serial.print(':');
    Serial.println(dt.second(), DEC);
}

creo que al modificar eso no afecta nada el código en general, lo probaré y te contaré luego.
De nuevo agradezco mucho por poner tus conocimientos y tu tiempo ayudándome, saludos

Muchas gracias me ha funcionado como esperaba (sólo cambie el pin CS del 4 al 10), leeré bien el código y la librería para entenderlo mejor y hacerle algunas modificaciones que necesito, soy nuevo en esto pero si hay algo que pueda hacer para ayudarte con gusto, saludos.

Daré el post como solucionado, si alguien está trabajando un proyecto similar y necesita que le brinde información no duden en comentar.