#include <SPI.h>
#include <SD.h>
File file;
String buffer;
int32_t session_val = 1;
uint32_t fileCounter = 1;
unsigned long lastMicros = 0;
char fileName[13];
/* Constants for Timing */
// unsigned long startAnalogTimer = 0; // Micros and Milis requires unsigned long
unsigned long endAnalogTimer = 0;
// unsigned long startFileTimer = 0;
unsigned long endFileTimer = 0;
bool fileWrite = true;
void setup() {
SPI_initialization(9600);
// reserve 1kB for String used as a buffer
buffer.reserve(1024);
if (!SD.begin()) {
Serial.println("Card failed, or not present");
while (1);
}
}
void loop() {
file = open_SD_tmp_File_sessionFile(fileCounter,session_val);
unsigned long startFileTimer = millis();
while ( (millis() - startFileTimer) < 50)
{
// Serial.println(millis()-startFileTimer);
unsigned long startAnalogTimer = micros();
while ( (micros() - startAnalogTimer) < 1000)
{
// Serial.println(micros() - startAnalogTimer);
// add a new line to the buffer
buffer += micros() - startAnalogTimer;
buffer += ",";
buffer += analogRead(A0);
buffer += "\r\n";
// Serial.println(buffer);
}
unsigned int chunkSize = file.availableForWrite();
if (chunkSize && buffer.length() >= chunkSize) {
// write to file
file.write(buffer.c_str(), chunkSize);
// remove written data from buffer
buffer.remove(0, chunkSize);
}
}
Serial.println("closing file");
file.close();
if (fileWrite) {
file = SD.open("00010001.txt");
// if the file is available, write to it:
if (file) {
Serial.print("opening... ");
Serial.println(file.name());
while (file.available()) {
Serial.write(file.read());
}
file.close();
}
// if the file isn't open, pop up an error:
else {
Serial.println("error opening datalog.txt");
}
delay(3000);
}
}
/*open_SD_tmp_File_sessionFile:
**Opens/Creates a file in the SD card
**Required: The file must be closed manually
**File name format: SSSSXXXX.txt S:session,X:file count
*/
File open_SD_tmp_File_sessionFile(int fileIndex, int session)
{
Serial.println("\nInitilizing write to file... ");
//.tmp
fourDigits(session, fileName);
fourDigits(fileIndex, fileName + 4);
snprintf(fileName + 8, 5, ".txt");
file = SD.open(fileName, FILE_WRITE);
if (file) {
Serial.println("File created successfully!");
} else {
Serial.println("Error opening file");
}
Serial.println(file.name());
return file;
}
void SPI_initialization(const uint32_t baudRate) {
Serial.begin(baudRate);
while (!Serial && millis() < 15000) {
;
}
Serial.println("\n\n-----New Serial Communication Secured-----");
}
char* fourDigits(int32_t digits, char* result) {
if (digits < 10) {
sprintf(result, "000%d", digits);
} else if (digits < 100) {
sprintf(result, "00%d", digits);
} else if (digits < 1000) {
sprintf(result, "0%d", digits);
} else {
sprintf(result, "%d", digits);
}
return result;
}