Skip to content

Commit e91bf0d

Browse files
authored
Merge pull request #115 from LeeLeahy2/sd-card-listing
Add read file support to SD_FileListing
2 parents 7f6d596 + c752bd6 commit e91bf0d

File tree

1 file changed

+73
-3
lines changed

1 file changed

+73
-3
lines changed

Firmware/Test Sketches/SD_FileListing/SD_FileListing.ino

Lines changed: 73 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66

77
#include "settings.h"
88

9+
#define ASCII_LF 0x0a
10+
#define ASCII_CR 0x0d
11+
912
int pin_microSD_CS = 25;
1013

1114
//microSD Interface
@@ -34,6 +37,10 @@ const TickType_t fatSemaphore_longWait_ms = 200 / portTICK_PERIOD_MS;
3437
uint32_t sdCardSizeMB = 0;
3538
uint32_t sdFreeSpaceMB = 0;
3639
uint32_t sdUsedSpaceMB = 0;
40+
41+
char filename[1024];
42+
uint8_t buffer[5701];
43+
3744
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
3845

3946
void setup()
@@ -52,9 +59,72 @@ void setup()
5259

5360
void loop()
5461
{
62+
int bytesRead;
63+
int bytesToRead;
64+
char data;
65+
int length;
66+
SdFile sdFile;
67+
SdFile sdRootDir;
68+
69+
// Read the filename
70+
Serial.println("\nPlease enter the filename:");
71+
length = 0;
72+
do {
73+
while (!Serial.available());
74+
data = Serial.read();
75+
if ((data == ASCII_LF) || (data == ASCII_CR))
76+
break;
77+
filename[length++] = data;
78+
} while (1);
79+
filename[length] = 0;
80+
81+
// Skip reading the SD card if no filename is specified
82+
if (length) {
83+
Serial.printf("filename: %s\n", filename);
84+
do {
85+
86+
// Attempt to open the root directory
87+
Serial.println("Attempting to open the root directory");
88+
sdRootDir = SdFile();
89+
if (!sdRootDir.openRoot(sd.vol())) {
90+
Serial.println("ERROR - Failed to open root directory!");
91+
break;
92+
}
93+
94+
// Attempt to open the file
95+
Serial.printf("Attempting to open file %s\n", filename);
96+
if (!sdFile.open(&sdRootDir, filename, O_RDONLY)) {
97+
// File not found
98+
Serial.println("ERROR - File not found!");
99+
sdRootDir.close();
100+
break;
101+
}
102+
Serial.printf("File %s opened successfully!\n", filename);
103+
104+
// Close the root directory
105+
Serial.println("Closing the root directory");
106+
sdRootDir.close();
107+
108+
// Read the file
109+
do {
110+
111+
// Read data from the file
112+
bytesToRead = sizeof(buffer);
113+
Serial.printf("Attempting to read %d bytes from %s\n", bytesToRead, filename);
114+
bytesRead = sdFile.read(buffer, bytesToRead);
115+
Serial.printf("bytesRead: %d\n", bytesRead);
116+
} while (bytesRead > 0);
117+
118+
// Close the file
119+
Serial.printf("Closing %s\n", filename);
120+
sdFile.close();
121+
Serial.println();
122+
} while (0);
123+
}
124+
125+
// Wait for user to confirm reset
55126
Serial.println("Press a key to reset");
56127

57-
if (Serial.available()) ESP.restart();
58-
59-
delay(1000);
128+
while (!Serial.available());
129+
ESP.restart();
60130
}

0 commit comments

Comments
 (0)