Pololu Robotics & Electronics
Menu
My account Comments or questions? About Pololu Contact Ordering information Distributors

Pololu Forum

SD card data logging in ESP32

hi,

I made a project to log Voltage every millisecond with timestamp (DS3231) using ESP32, but i am getting data every 10 millisecond after some time the logging speed is reducing as time elapses . how to keep same logging speed throughout the process .

this is my code:

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

float volt1,volt2;
float offset =0;

RTC_DS1307 rtc;

void writeFile(fs::FS &fs, const char * path, const char * message){
    //Serial.printf("Writing file: %s\n", path);

    File file = fs.open(path, FILE_WRITE);
    if(!file){
        Serial.println("Failed to open file for writing");
        return;
    }
    if(file.print(message)){
        Serial.println("File written");
    } else {
        Serial.println("Write failed");
    }
    file.close();
}

void appendFile(fs::FS &fs, const char * path, const char * message){
    //Serial.printf("Appending to file: %s\n", path);

    File file = fs.open(path, FILE_APPEND);
    if(!file){
       // Serial.println("Failed to open file for appending");
        return;
    }
    if(file.print(message)){
       // Serial.println("Message appended");
    } else {
        //Serial.println("Append failed");
    }
    file.close();
}

void setup(){
  Serial.begin(115200);
  
  
  if(!SD.begin()){
      Serial.println("Card Mount Failed");
      return;
      }

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
    }

  if (!rtc.isrunning()) {
    Serial.println("RTC lost power, lets set the time!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
  
  writeFile(SD, "/MC02.txt", "Feeder Current \r\n");
}

void loop(){

   float volt = analogRead(A0);// read the input
   double voltage = map(volt,0,1023, 0, 2500) + offset;
   voltage /=100;

   volt1=voltage-5;
   volt2=volt1*800;

  
  String dataString = "";

  

  DateTime now = rtc.now();

  dataString += String(now.day(), DEC);
  dataString += "/";
  dataString += String(now.month(), DEC);
  dataString += "/";
  dataString += String(now.year(), DEC);
  dataString += ",";
  dataString += String(now.hour(), DEC);
  dataString += ":";
  dataString += String(now.minute(), DEC);
  dataString += ":";
  dataString += String(now.second(), DEC);
  dataString += ",";
  
  dataString += String(voltage);
  dataString += ",";
  dataString += String(volt2);
  dataString += "\r\n";

  Serial.println(dataString);
  appendFile(SD, "/MC02.txt", dataString.c_str());
    
}

Hello.

Writing to an SD card every millisecond might be incurring excessive overhead (and also might not be great for the SD card). You might consider buffering the data and writing it in bigger chunks less often to see if it helps.

Brandon