#include <SD.h>
#include "RTClib.h"
#define FILE_NAME "MyData.csv"
RTC_DS1307 rtc;
const int cs = 10; // Set the chip select pin for your SD card module
uint8_t count = 1;
float f = 0.0;
char timeStamp[32];
bool toOpen = true;
File dataFile;
void setup() {
Serial.begin(115200);
while (!Serial) {
; // Wait for serial port to connect
}
Serial.print("Initializing SD card...");
if (!SD.begin(cs)) {
Serial.println("SD card initialization failed.");
return;
} else {
Serial.println("SD card initialized successfully.\nWait 36sec approx\n");
}
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
return;
}
}
void loop() {
if (count < 37) {
if (toOpen) {
dataFile = SD.open(FILE_NAME, FILE_WRITE);
toOpen = false;
}
/*
if (dataFile) {
Serial.println(F("File is open"));
} else {
Serial.print(F("SD Card: error on opening file "));
//Serial.println(FILE_NAME);
}
Serial.println(F("Writing log to SD Card"));
*/
DateTime now = rtc.now();
sprintf(timeStamp, "%04d-%02d-%02d %02d:%02d:%02d, ", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second());
dataFile.print(timeStamp);
f = random(1234, 5678) / 100.0;
dataFile.println(f);
if (count % 6 == 0) dataFile.println("\t\t ,\t <--- Empty Row\n\t\t ,\t <--- Empty Row");
count++;
delay(1000); // Wait for 1 second
}
if (count == 37) {
dataFile.close();
delay(1000);
dataFile = SD.open(FILE_NAME, FILE_READ);//Reopen in READ mode
if (dataFile) {
while (dataFile.available()) { // Read the data from the file
Serial.write(dataFile.read());
}
dataFile.close(); // Close the file
count = 0;
Serial.println("STOP THE SIMULATION");
}
}
}