This is a sample of reading and writing a text file saved in an SD card with ESP32.
I couldn't find much simple sample code on the net to read and write, so I drew it.
I used this site as a reference for wiring between the SD card and ESP.
And I used this code as a reference.
Save data to SD card with Arduino
Reference: mgo-tec電子工作
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <SD.h> | |
#define LOG_FILE_NAME "/log.txt" | |
const uint8_t SD_CS = 5; // GPIO5=CS | |
static File s_myFile; | |
void SD_init() | |
{ | |
Serial.print("Initializing SD card..."); | |
if (!SD.begin(SD_CS)) { | |
Serial.println("initialization failed!"); | |
return; | |
} | |
Serial.println("initialization done."); | |
} | |
String SD_read() { | |
String str; | |
File file = SD.open(LOG_FILE_NAME, FILE_READ); | |
if(file){ | |
//---1byteずつ読み込んだ文字を結合 | |
while (file.available()) { | |
str += char(file.read()); | |
} | |
} else{ | |
Serial.println(" error..."); | |
} | |
//---ファイルを閉じる | |
file.close(); | |
return str; | |
} | |
void SD_write() | |
{ | |
String backLog = SD_read(); | |
s_myFile = SD.open(LOG_FILE_NAME, FILE_WRITE); | |
if (s_myFile) { | |
Serial.print("Writing to test.txt..."); | |
s_myFile.print(backLog); | |
s_myFile.println("Hello, World"); | |
s_myFile.close(); | |
Serial.println("done."); | |
} else { | |
Serial.println("error opening test.txt"); | |
} | |
} | |
void setup() { | |
Serial.begin(115200); | |
while(!Serial); | |
Serial.println(); | |
SD_init(); | |
SD_write(); | |
Serial.println(SD_read()); | |
} | |
void loop() { | |
// put your main code here, to run repeatedly: | |
} |