Advertisement
microrobotics

MicroSD Card Module - 6 Pin

Apr 13th, 2023 (edited)
2,464
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Here's some sample code to interface a micro SD card module with ESP32 over SPI using the Arduino IDE:
  3.  
  4. In this code, we first define the chip select pin for the SD card module as SD_CS_PIN and initialize the SPI communication using SPI.begin(). We then initialize the SD card using SD.begin() and check if it was successful using an if statement.
  5.  
  6. In the loop() function, we open a file named data.txt on the SD card using SD.open(), and then read and print the contents of the file using a while loop and Serial.write(). Finally, we close the file using dataFile.close() and add a delay of 1 second before repeating the loop.
  7.  
  8. Note that you'll need to install the "SD" library in the Arduino IDE in order to use the SD functions.
  9. */
  10.  
  11. #include <SPI.h>
  12. #include <SD.h>
  13.  
  14. #define SD_CS_PIN 5 // Chip select pin for SD card
  15.  
  16. void setup() {
  17.   Serial.begin(9600);
  18.  
  19.   // Initialize SPI communication
  20.   SPI.begin();
  21.  
  22.   // Initialize SD card
  23.   if (!SD.begin(SD_CS_PIN)) {
  24.     Serial.println("Failed to initialize SD card");
  25.     return;
  26.   }
  27.  
  28.   Serial.println("SD card initialized successfully");
  29. }
  30.  
  31. void loop() {
  32.   // Read data from a file on SD card
  33.   File dataFile = SD.open("data.txt");
  34.  
  35.   if (dataFile) {
  36.     while (dataFile.available()) {
  37.       Serial.write(dataFile.read());
  38.     }
  39.     dataFile.close();
  40.   } else {
  41.     Serial.println("Failed to open data file");
  42.   }
  43.  
  44.   delay(1000);
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement