Advertisement
microrobotics

D1 Mini Micro SD Card Module

Mar 31st, 2023
3,440
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Here's an example on how to use a Micro SD card module with a Wemos D1 Mini (ESP8266) to read and write data to a text file. This example uses the SD and SPI libraries that come with the Arduino IDE.
  3.  
  4. Connect the Micro SD card module to your Wemos D1 Mini as follows:
  5.  
  6. VCC to 3.3V
  7. GND to GND
  8. MISO to D6
  9. MOSI to D7
  10. SCK to D5
  11. CS to D8
  12. Upload the complete code to your Wemos D1 Mini and open the Serial Monitor. The program will create a file called "test.txt",
  13. */
  14.  
  15. #include <ESP8266WiFi.h>
  16. #include <SPI.h>
  17. #include <SD.h>
  18.  
  19. #define CS_PIN D8
  20.  
  21. void setup() {
  22.   Serial.begin(115200);
  23.   Serial.println("Initializing SD card...");
  24.  
  25.   if (!SD.begin(CS_PIN)) {
  26.     Serial.println("Initialization failed!");
  27.     return;
  28.   }
  29.   Serial.println("Initialization successful.");
  30. }
  31.  
  32. void loop() {
  33.   File dataFile = SD.open("test.txt", FILE_WRITE);
  34.   if (dataFile) {
  35.     dataFile.println("Hello, world!");
  36.     dataFile.close();
  37.     Serial.println("Data written to test.txt");
  38.   } else {
  39.     Serial.println("Failed to create test.txt");
  40.   }
  41.  
  42.   dataFile = SD.open("test.txt");
  43.   if (dataFile) {
  44.     Serial.println("Reading data from test.txt:");
  45.     while (dataFile.available()) {
  46.       Serial.write(dataFile.read());
  47.     }
  48.     dataFile.close();
  49.   } else {
  50.     Serial.println("Failed to open test.txt for reading");
  51.   }
  52.  
  53.   if (SD.remove("test.txt")) {
  54.     Serial.println("test.txt has been deleted");
  55.   } else {
  56.     Serial.println("Failed to delete test.txt");
  57.   }
  58.  
  59.   delay(5000);
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement