Home › Forums › Mayfly Data Logger › How to dump contents of file on SD card to serial › Reply To: How to dump contents of file on SD card to serial
2021-07-13 at 1:58 PM
#15665
Hi @Selbig. Here is a very simple sketch that prints a file from the microSD card to the serial monitor. It might be too rudimentary for your purposes, but thought I would share it here. Notice the line “// SD.remove(“datalog.txt”);” is commented out. Uncomment this line to DELETE the file specified instead of printing it to the serial monitor. I find it is helpful for my work to have this option available when I need it.
Arduino
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
//This sketch displays the files on a Mayfly Data Logger microSD card to the serial monitor and then outputs //a specific file named in the sketch below to the serial monitor. #include <SPI.h> #include <SD.h> File root; void setup() { Serial.begin(9600); // Open serial communications and wait for port to open while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } Serial.print("Initializing SD card..."); if (!SD.begin(12)) { // digital pin 12 is the microSD slave select pin on Mayfly; see if the card is present and can be initialized Serial.println("Card failed, or not present"); // don't do anything more while (1); } Serial.println("card initialized."); Serial.println(""); root = SD.open("/"); Serial.println("Files on microSD card"); printDirectory(root, 0); Serial.println(""); Serial.println("Displaying file:"); // SD.remove("datalog.txt"); // THE NUCLEAR OPTION!!! UNCOMMENT TO DELETE THE FILE! File dataFile = SD.open("datalog.txt"); // Name the file to be opened. if (dataFile) { // if the file is available, write to it: while (dataFile.available()) { Serial.write(dataFile.read()); } dataFile.close(); } else { Serial.println("error opening datalog.txt"); // if the file isn't open, pop up an error: } } void loop() { // put your main code here, to run repeatedly: } void printDirectory(File dir, int numTabs) { //This is a function that displays all the files on the SD card to the serial monitor. while (true) { File entry = dir.openNextFile(); if (! entry) { // no more files break; } for (uint8_t i = 0; i < numTabs; i++) { Serial.print('\t'); } Serial.print(entry.name()); if (entry.isDirectory()) { Serial.println("/"); printDirectory(entry, numTabs + 1); } else { // files have sizes, directories do not Serial.print("\t\t"); Serial.println(entry.size(), DEC); } entry.close(); } } |