#include <SPI.h>
#include <SD.h>
// Chip select pin for the SD card module
const int chipSelect = 10;
void setup() {
// Start the serial communication
Serial.begin(9600);
Serial.println("Initializing SD card...");
// Check if the SD card is present and can be initialized
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// Don't do anything more
return;
}
Serial.println("Card initialized.");
// Open a file for writing
File dataFile = SD.open("example.txt", FILE_WRITE);
// If the file is available, write to it
if (dataFile) {
dataFile.println("Hello, Wokwi!");
dataFile.close(); // Close the file
Serial.println("Writing to example.txt done.");
} else {
// If the file didn't open, print an error
Serial.println("Error opening example.txt");
}
// Open the file for reading
dataFile = SD.open("example.txt");
if (dataFile) {
Serial.println("example.txt contents:");
// Read from the file until there's nothing else in it
while (dataFile.available()) {
Serial.write(dataFile.read());
}
dataFile.close(); // Close the file
} else {
// If the file didn't open, print an error
Serial.println("Error opening example.txt");
}
}
void loop() {
// Nothing to do here
}