#include <WiFi.h>
#include <WebServer.h>
#include <SPI.h>
#include <SD.h>
// Replace with your network credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
WebServer server(80);
const int chipSelect = 5;
void setup() {
Serial.begin(115200);
delay(1000);
// Initialize SD card
if (!SD.begin(chipSelect)) {
Serial.println("SD Card initialization failed!");
return;
}
Serial.println("SD Card initialized.");
// Connect to Wi-Fi
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
int attempt = 0;
while (WiFi.status() != WL_CONNECTED && attempt < 20) { // limit attempts to 20
delay(500);
Serial.print(".");
attempt++;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("");
Serial.println("WiFi connected.");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
} else {
Serial.println("");
Serial.println("Failed to connect to WiFi.");
return;
}
// Define server routes
server.on("/", HTTP_GET, handleRoot);
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
}
void handleRoot() {
String html = "<html><body><h1>SD Card File List</h1><ul>";
File root = SD.open("/");
if (!root) {
Serial.println("Failed to open directory");
return;
}
if (!root.isDirectory()) {
Serial.println("Not a directory");
return;
}
File file = root.openNextFile();
while (file) {
if (!file.isDirectory()) {
html += "<li><a href='/download?file=" + String(file.name()) + "'>" + String(file.name()) + "</a></li>";
}
file = root.openNextFile();
}
html += "</ul></body></html>";
server.send(200, "text/html", html);
}
void handleNotFound() {
if (server.uri().startsWith("/download")) {
handleFileDownload();
} else {
server.send(404, "text/plain", "Not Found");
}
}
void handleFileDownload() {
String filename = server.arg("file");
if (filename.length() == 0) {
server.send(400, "text/plain", "File name not specified");
return;
}
File file = SD.open(filename);
if (!file) {
server.send(404, "text/plain", "File not found");
return;
}
server.streamFile(file, "application/octet-stream");
file.close();
}