Hi all, I'm getting some weird behavior from my Nano that I'm using to write a text file to an SD card. In short, what I'm trying to do is check the SD card for files called "test1.txt", "test2.txt", "test3.txt", etc etc. and then creating (for example) a "test4.txt" file when "test4.txt" does not exist. Here's my code:
#include <SPI.h>
#include <SD.h>
const int chipSelect = 4;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
SD.begin(chipSelect);
String fileName = "test1.txt";
int i = 1;
File dataFile = SD.open(fileName);
while(i > 0){
dataFile = SD.open(fileName);
if(dataFile) {
Serial.println(fileName + " exists");
i += 1;
dataFile.close();
fileName = "test" + String(i) + ".txt";
}else{
i = 0;
Serial.println(fileName + " does not exist");
Serial.println("Creating "+ fileName);
dataFile = SD.open(fileName, FILE_WRITE);
Serial.println("Success!");
}
}
}
Note: void loop() {} is empty
If "test1.txt", "test2.txt", "test3.txt" already exist on the SD card, the output on the serial monitor looks like this:
test1.txt exists
test2.txt exists
test3.txt exists
test4.txt does not exist
Creating test4.txt
test1.txt exists
test2.txt exists
test3.txt exists
test4.txt exists
test5.txt does not exist
Creating test5.txt
Success!
Any idea what's going on here?
I wired the Nano according to this tutorial:https://www.circuito.io/app?components=9442,11022,1671987
Except I connect CS to D4