I want to use my ESP32 board to write on my SD card. using the example that comes with the esp32 board package, all things are OK. But when I wrote my own code, It can not open the file to write in it.
Code: Select all
#include "FS.h"
#include "SD.h"
#include "SPI.h"
bool sdInitSuccess = false;
#define SDWRITETIME 60000
char CurrentFileName[128];
#define SD_CS_PIN 5 // Le lecteur de SD card sera branché sur les pins G5 (CS)
bool sdfileOpend = false;
void WriteSDcard()
{
File myFile;
static unsigned long T = 0;
if(!sdInitSuccess){
Serial.println("Initializing SD card...");
if (!SD.begin()) {
Serial.println("Initialization failed!\n");
return;
} //failure
else {
Serial.println("Intitialization success.\n");
sdInitSuccess = true;
}
}
if (millis() < T) return;
T = millis() + SDWRITETIME;
char FileName[128];
char fileHeader[] = "Date;Time;T1;H1;T2;H2";
sprintf(FileName, "test30.txt");
if (strcmp(CurrentFileName, FileName)) {
strcpy(CurrentFileName, FileName);
}
if (sdfileOpend == 0) {
bool myFileExist = SD.exists("test30.txt");
myFile = SD.open("test30.txt", FILE_WRITE);
Serial.println(myFileExist);
Serial.println(myFile);
// if (myFile) {
// }
if(!myFile) {
Serial.print("can not open File for Writing: ");
Serial.println(CurrentFileName);
return;
}
Serial.print(F("File opened for Writing successfully:"));
sdfileOpend = 1;
if (!myFileExist) {
myFile.println(fileHeader);
}
Serial.println(CurrentFileName);
}
if(myFile.print(16))
Serial.println("Written");
else
Serial.println("Failed to write");
myFile.print("/");
myFile.print(10);
myFile.print("/");
myFile.print(2023);
myFile.print(";");
myFile.print(10);
myFile.print(":");
myFile.print(48);
myFile.print(":");
myFile.print(7);
myFile.print(";");
myFile.print(40);
myFile.print(";");
myFile.print(35);
myFile.print(";");
myFile.print(3);
myFile.print(";");
myFile.print(2.5);
myFile.print(";");
myFile.print(40);
myFile.print(";");
myFile.print(25);
myFile.print(";");
myFile.print(30);
myFile.print(";");
myFile.print(35);
myFile.print(";");
myFile.print(45);
myFile.print(";");
myFile.print(20);
myFile.print(";");
myFile.close();
sdfileOpend = 0;
Serial.println("Data written to SD card");
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
}
void loop() {
WriteSDcard();
// put your main code here, to run repeatedly:
}
Code: Select all
Initializing SD card...
Intitialization success.
0
0
can not open File for Writing: test30.txt
0
0
can not open File for Writing: test30.txt
what could be the problem?