Dear All,
I’m new in the Arduino World. Maybe already somebody else has posted the same problem already before, but on my research on the forum as well as on googling I could found no idea, what I’m doing wrong. Maybe someone finds my mistake.
The Aim of the small Project:
I have a Button and an SD-Card Modul.
I push the Button and Arduino counts the files on the SD card and writes a textfile with the name count+1
The Problem:
When I push the button the first time it works like it should.
If I push it the second + time, the counting does not work (gives 000.txt)
Trials:
If I let run the writing before the counting it also does not count right.
Question:
Why is this like this?
What did I wrong?
How can I bypass this?
Thanks a lot in advance for your support and help
Attached my code.
//Button 1
const int buttonPin1 =2; // the number of the pushbutton pin
int buttonState1 = 0; // variable for reading the pushbutton status
//SD Card
#include <SD.h>
const int chipSelect = 10;
void setup()
{
Serial.begin(9600);
//Button 1
pinMode(buttonPin1, INPUT); // initialize the pushbutton pin as an input:
//SD Card
Serial.print("Initializing SD card...");
pinMode(10, OUTPUT);
// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
return;
}
Serial.println("card initialized.");
}
void loop()
{
//Button1
buttonState1 = digitalRead(buttonPin1);
// check if the pushbutton 1 is pressed.
if (buttonState1 == 1){
String filename=sdFilecount();
writeonSD(filename);
}
delay (500);
}
void writeonSD(String filename){
String dataString="This is a Test";
File dataFile = SD.open(filename, FILE_WRITE);
if (dataFile) {
dataFile.println(dataString);
dataFile.close();
Serial.println("File Written");
}
dataFile.close();
}
String sdFilecount( ) {
File dir = SD.open("/");
int numTabs=0;
int countfile= 0;
while (true) {
File entry = dir.openNextFile();
//Serial.println(entry);
if (! entry) {
break;
}
for (uint8_t i = 0; i < numTabs; i++) {
}
//Serial.println(entry.name());
countfile++;
entry.close();
}
dir.close();
String countString="";
countfile++;
if (countfile<100){countString+="0";}
if (countfile<10){countString+="0";}
countString+=String(countfile);
countString+=".txt";
Serial.println("****************");
Serial.println(countString);
return (countString);
}