ESP32 SD Card Read/write Example
Introduction
ESP32 Wi-Fi Modes -
The ESP32 board can act as Wi-Fi Station, Access Point or both. To set the Wi-Fi mode, use WiFi.mode() and set the desired mode as argument:
WiFi.mode(WIFI_STA) - station mode: the ESP32 connects to an access point
WiFi.mode(WIFI_AP) - access point mode: stations can connect to the ESP32
WiFi.mode(WIFI_AP_STA) - access point and a station connected to another access point
Wi-Fi Station -
When the ESP32 is set as a Wi-Fi station, it can connect to other networks (like your router). Your can connect to ESP using the IP address assigned by router.
Access Point -
When you set your ESP32 board as an access point, it creates its own Wi-Fi network and you can be connect any device with Wi-Fi capabilities to your ESP32 board.
Wi-Fi Station + Access Point -
The ESP32 can be set as a Wi-Fi station and access point simultaneously.
Scan Wi-Fi Networks -
The ESP32 can scan nearby Wi-Fi networks within its Wi-Fi range.
Step 1: Connect Board to Laptop
Step 2: Scan Wi-Fi Networks Example Code
Select boar ESP32 DEV Module from Tools >> Boards menu, then select appropriate com port. Upload this program to ESP32.
/*
SD Card Interface code for ESP32
SPI Pins of ESP32 SD card as follows:
CS = 5;
MOSI = 23;
MISO = 19;
SCK = 18;
*/
#include <SPI.h>
#include <SD.h>
File myFile;
const int CS = 5;
//WriteFile
void WriteFile(const char * path, const char * message){
// open the file.
// Note - only one file can be open at a time
// close the opened file before opening another file
myFile = SD.open(path, FILE_WRITE);
// if the file open fine, then write to the file
if (myFile) {
myFile.println(message);
myFile.close(); // close the file
Serial.println("completed.");
}
// if the file didn't open then print an error
else {
Serial.println("error opening file ");
Serial.println(path);
}
}
//ReadFile
void ReadFile(const char * path){
// open the file for reading:
myFile = SD.open(path);
if (myFile) {
Serial.printf("Reading file from %s\n", path);
// read from the file until there's nothing else in it:
while (myFile.available()) {
Serial.write(myFile.read());
}
myFile.close(); // close the file
}
else {
// if the file didn't open then print an error
Serial.println("error opening test.txt");
}
}
void setup() {
Serial.begin(9600);
delay(500);
while (!Serial) { ; } // wait for serial port to connect
Serial.println("Initializing SD card...");
if (!SD.begin(CS)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
WriteFile("/test.txt", "Cheers 2 Engineering - SD Card test");
ReadFile("/test.txt");
}
void loop() {
// nothing happens after setup
}