I am working on a simple code to write data to a MicroSD card using Arduino nano ESP32 (ABX0083) and Df robot SPI MicroSD card module(DFR0229). I am not able to write to the SD card. I get the error condition "Error opening dta.txt for writing.".
- All pins are connected correctly. SD.h module is used. Pins are connected according to arduino nano-ESP pinout https://docs.arduino.cc/resources/pinouts/ABX00083-full-pinout.pdf
The default pinout used is"Arduino". The code works well with Arduino UNO. Following is the code.
#include <SPI.h>
#include <SD.h>
// Define the chip select pin for the SD card module
const int chipSelect = 10;
void setup() {
// Start the serial communication
Serial.begin(9600);
//pinMode(chipSelect, OUTPUT);
pinMode(chipSelect, OUTPUT);
while (!Serial) {
// Wait for the serial port to connect (needed for Leonardo and Micro)
}
Serial.println("Initializing SD card...");
// Initialize the SD card
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// Don't do anything more
while (1);
}
Serial.println("Card initialized.");
// Open the existing file for writing
File dataFile = SD.open("dta.txt", FILE_WRITE);
// Check if the file opened successfully
if (dataFile) {
Serial.println("Writing to dta.txt...");
// Write some example data
dataFile.println("Appending new data");
// Close the file
dataFile.close();
Serial.println("Data written to dta.txt successfully.");
} else {
// If the file didn't open, print an error
Serial.println("Error opening dta.txt for writing.");
}
}
void loop() {
// Nothing to do here
}