I have this code that works;however I'm trying to generalise it by making the procedures into functions, following the SPIFFS example. However the readInt function is not giving correct values - it seems to read the wrong file. Any suggestions?
#include "SPIFFS.h"
int wData[] = {11, 112, 1234, 12345, 3456, 567}; //ASCII "1" = 48, "2"=49, "LF"=10, "SP" =32
void setup() {
Serial.begin(115200);
if (!SPIFFS.begin(true)) {
Serial.println("An Error has occurred while mounting SPIFFS");
return;
}
File file = SPIFFS.open("/test.txt", FILE_WRITE);
if (!file) {
Serial.println("There was an error opening the file for writing");
return;
}
// my function to add an integer to the file
for (int i = 0; i < 6; i++) {
appendInt(SPIFFS, "/test.txt", wData[i]);
}
file = SPIFFS.open("/test.txt");
if (!file) {
Serial.println("Failed to open file for reading");
return;
}
Serial.println("File Content:");
while (file.available()) {
//my function to read an integer from the file
//int x = readInt(SPIFFS, "/test.txt");
//this code works; but when I put it into a function it disnae?
char iBuffer[10]; //integer range is -32768 ie 6 chars
int x = file.readBytesUntil('\n', iBuffer, sizeof(iBuffer) - 1);
iBuffer[x] = 0; //ensure char array is null terminated for atoi
Serial.print("iBuffer holds ");
Serial.print(iBuffer);
Serial.print(": rData is ");
int rData = atoi (iBuffer);
Serial.println(rData);
}
file.close();
}
void loop() {}
and here are the functions:
//SPIFFS functions to write and read an integer
//write a single integer to a file: example appendInt(SPIFFS, fileName, data);
//note file must already be open for writing
void appendInt(fs::FS &fs, const char * path, int iData) {
File file = fs.open(path, FILE_APPEND);
if (!file) {
Serial.println("appendInt: - failed to open file to append data");
return;
}
char dBuffer[10]; //integer range is -32768 ie 6 digits so allow plenty space
snprintf(dBuffer, sizeof(dBuffer), " %i", iData); //leading whitespace is ignored by atoi
if (file.println(dBuffer)) { // character string ends with a "\n"
Serial.println(dBuffer);
} else {
Serial.println("File write failed");
}
file.close();
}
//read a single integer from a SPIFFS file:
int readInt(fs::FS &fs, const char * path) {
Serial.printf("Reading from file: %s\r\n", path);
File file = fs.open(path);
if (!file) {
Serial.println("readInt: - failed to open file for reading");
return (0);
}
char iBuffer[10]; //integer range is -32768 ie 6 chars
int x = file.readBytesUntil('\n', iBuffer, sizeof(iBuffer) - 1);
iBuffer[x] = 0; //ensure char array is null terminated for atoi
Serial.print(": rData is ");
int rData = atoi (iBuffer);
Serial.println(rData);
//file.close();
return (rData);
}