upload file wav to SD memory in Teensy 4.1 with Nativethernet by hmtl page

marcellom66

New member
I need to upload a file wav to Teensy 4.1 by ethernet and save it to SD memory but my program doesn't work, do you know a library that it's right for this function or if I write something wrong, thanks for your help.

This is my program:

#include <NativeEthernet.h>
#include <SD.h>
#include <stdlib.h> // necessario per qsort

// Inizializza la connessione Ethernet e il server Web
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 177);
EthernetServer server(80);

void setup() {
Ethernet.begin(mac, ip);
server.begin();
if (!SD.begin(BUILTIN_SDCARD)) {
Serial.println("Errore durante l'inizializzazione della memoria SD.");
return;
}
}

void loop() {
EthernetClient client = server.available();
if (client) {
if (client.connected()) {
String request = "";
while (client.available()) {
char c = client.read();
request += c;
if (request.endsWith("\r\n\r\n")) {
break;
}
}
if (request.indexOf("POST") >= 0) {
int nameStart = request.indexOf("filename=\"") + 10;
int nameEnd = request.indexOf("\"", nameStart);
String fileName = request.substring(nameStart, nameEnd);
int sizeStart = request.indexOf("Content-Length: ") + 16;
int sizeEnd = request.indexOf("\r\n", sizeStart);
int fileSize = request.substring(sizeStart, sizeEnd).toInt();
File file = SD.open(fileName.c_str(), O_RDWR | O_CREAT);
int bytesWritten = 0;
while (bytesWritten < fileSize) {
if (client.available()) {
char c = client.read();
file.write(c);
bytesWritten++;
}
}
file.close();
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
client.println("<html>");
client.println("<head>");
client.println("<title>Upload File su Teensy 4.1</title>");
client.println("</head>");
client.println("<body>");
client.println("<h1>File caricato con successo!</h1>");
client.println("<p>Il file " + fileName + " è stato caricato correttamente sulla memoria SD di Teensy 4.1.</p>");
client.println("<p><a href=\"/\">Torna all'elenco dei file sulla memoria SD</a></p>");
client.println("</body>");
client.println("</html>");
delay(10);
client.stop();
}
else if (request.indexOf("GET") >= 0) {
handleGetRequest(client);
}
else {
handleBadRequest(client);
}
}
}
}

// funzione di comparazione per qsort
int compare(const void *a, const void *b) {
String *strA = (String *)a;
String *strB = (String *)b;
return strA->compareTo(*strB);
}

void handleGetRequest(EthernetClient client) {
File root = SD.open("/");
if (!root) {
Serial.println("Errore nell'apertura della root directory");
client.println("HTTP/1.1 500 Internal Server Error");
client.println("Content-Type: text/html");
client.println();
client.println("<h1>Errore interno del server</h1>");
return;
}

String fileList[20];
int fileCount = 0;
while (File entry = root.openNextFile()) {
if (entry.isDirectory()) {
entry.close();
continue;
}
fileList[fileCount] = entry.name();
entry.close();
fileCount++;
if (fileCount >= 20) {
break;
}
}
root.close();

qsort(fileList, fileCount, sizeof(String), compare);

client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
client.println();

client.println("<html>");
client.println("<head>");
client.println("<title>Directory listing</title>");
client.println("<style>");
client.println("table { border-collapse: collapse; width: 25%; }");
client.println("th, td { text-align: left; padding: 8px; }");
client.println("th { background-color: #777; color: white; border: 2px solid black; }");
client.println("tr:nth-child(even) { background-color: #f2f2f2; }");
client.println(".scrollbar { height: 200px; overflow-y: scroll; }");
client.println("</style>");
client.println("</head>");
client.println("<body>");
client.println("<h2>Directory listing</h2>");

client.println("<form action=\"/upload\" method=\"post\" enctype=\"multipart/form-data\">");
client.println("<input type=\"file\" name=\"fileToUpload\" style=\"font-size: 16px; padding: 8px;\">");
client.println("<input type=\"submit\" value=\"Scegli file\" style=\"font-size: 16px; padding: 8px;\">");
client.println("<input type=\"submit\" value=\"Carica\" style=\"font-size: 16px; padding: 8px;\">");
client.println("</form>");

client.println("<table>");
client.println("<tr><th>Nome</th><th>Dimensione</th></tr>");

for (int i = 0; i < fileCount; i++) {
String fileName = fileList;
File entry = SD.open(fileName.c_str());
if (!entry) {
Serial.println("Errore nell'apertura del file: " + fileName);
continue;
}
if (entry.isDirectory()) {
entry.close();
continue;
}
client.println("<tr>");
client.println("<td>" + fileName + "</td>");
client.println("<td>" + String(entry.size()) + " bytes</td>");
client.println("</tr>");
entry.close();
}
client.println("</table>");

client.println("</body>");
client.println("</html>");
}



// Gestisce le richieste non valide
void handleBadRequest(EthernetClient client) {
client.println("HTTP/1.1 400 Bad Request");
client.println("Content-Type: text/html");
client.println();
client.println("<html>");
client.println("<head>");
client.println("<title>Richiesta non valida</title>");
client.println("</head>");
client.println("<body>");
client.println("<h1>Richiesta non valida</h1>");
client.println("<p>La richiesta inviata non è valida. Riprova.</p>");
client.println("</body>");
client.println("</html>");
delay(10);
client.stop();
}
 
Code:
#include <NativeEthernet.h>
#include <SD.h>
#include <stdlib.h> // necessario per qsort

// Inizializza la connessione Ethernet e il server Web
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 177);
EthernetServer server(80);

void setup() {
	Ethernet.begin(mac, ip);
	server.begin();
	if (!SD.begin(BUILTIN_SDCARD)) {
		Serial.println("Errore durante l'inizializzazione della memoria SD.");
		return;
	}
}

void loop() {
	EthernetClient client = server.available();
	if (client) {
		if (client.connected()) {
			String request = "";
			while (client.available()) {
				char c = client.read();
				request += c;
				if (request.endsWith("\r\n\r\n")) {
					break;
				}
			}
			if (request.indexOf("POST") >= 0) {
				int nameStart = request.indexOf("filename=\"") + 10;
				int nameEnd = request.indexOf("\"", nameStart);
				String fileName = request.substring(nameStart, nameEnd);
				int sizeStart = request.indexOf("Content-Length: ") + 16;
				int sizeEnd = request.indexOf("\r\n", sizeStart);
				int fileSize = request.substring(sizeStart, sizeEnd).toInt();
				File file = SD.open(fileName.c_str(), O_RDWR | O_CREAT);
				int bytesWritten = 0;
				while (bytesWritten < fileSize) {
					if (client.available()) {
						char c = client.read();
						file.write(c);
						bytesWritten++;
					}
				}
				file.close();
				client.println("HTTP/1.1 200 OK");
				client.println("Content-Type: text/html");
				client.println();
				client.println("<html>");
				client.println("<head>");
				client.println("<title>Upload File su Teensy 4.1</title>");
				client.println("</head>");
				client.println("<body>");
				client.println("<h1>File caricato con successo!</h1>");
				client.println("<p>Il file " + fileName + " è stato caricato correttamente sulla memoria SD di Teensy 4.1.</p>");
				client.println("<p><a href=\"/\">Torna all'elenco dei file sulla memoria SD</a></p>");
				client.println("</body>");
				client.println("</html>");
				delay(10);
				client.stop();
			}
			else if (request.indexOf("GET") >= 0) {
				handleGetRequest(client);
			}
			else {
				handleBadRequest(client);
			}
		}
	}
}

// funzione di comparazione per qsort
int compare(const void* a, const void* b) {
	String* strA = (String*)a;
	String* strB = (String*)b;
	return strA->compareTo(*strB);
}

void handleGetRequest(EthernetClient client) {
	File root = SD.open("/");
	if (!root) {
		Serial.println("Errore nell'apertura della root directory");
		client.println("HTTP/1.1 500 Internal Server Error");
		client.println("Content-Type: text/html");
		client.println();
		client.println("<h1>Errore interno del server</h1>");
		return;
	}

	String fileList[20];
	int fileCount = 0;
	while (File entry = root.openNextFile()) {
		if (entry.isDirectory()) {
			entry.close();
			continue;
		}
		fileList[fileCount] = entry.name();
		entry.close();
		fileCount++;
		if (fileCount >= 20) {
			break;
		}
	}
	root.close();

	qsort(fileList, fileCount, sizeof(String), compare);

	client.println("HTTP/1.1 200 OK");
	client.println("Content-Type: text/html");
	client.println("Connection: close");
	client.println();

	client.println("<html>");
	client.println("<head>");
	client.println("<title>Directory listing</title>");
	client.println("<style>");
	client.println("table { border-collapse: collapse; width: 25%; }");
	client.println("th, td { text-align: left; padding: 8px; }");
	client.println("th { background-color: #777; color: white; border: 2px solid black; }");
	client.println("tr:nth-child(even) { background-color: #f2f2f2; }");
	client.println(".scrollbar { height: 200px; overflow-y: scroll; }");
	client.println("</style>");
	client.println("</head>");
	client.println("<body>");
	client.println("<h2>Directory listing</h2>");

	client.println("<form action=\"/upload\" method=\"post\" enctype=\"multipart/form-data\">");
	client.println("<input type=\"file\" name=\"fileToUpload\" style=\"font-size: 16px; padding: 8px;\">");
	client.println("<input type=\"submit\" value=\"Scegli file\" style=\"font-size: 16px; padding: 8px;\">");
	client.println("<input type=\"submit\" value=\"Carica\" style=\"font-size: 16px; padding: 8px;\">");
	client.println("</form>");

	client.println("<table>");
	client.println("<tr><th>Nome</th><th>Dimensione</th></tr>");

	for (int i = 0; i < fileCount; i++) {
		String fileName = fileList[i];
		File entry = SD.open(fileName.c_str());
		if (!entry) {
			Serial.println("Errore nell'apertura del file: " + fileName);
			continue;
		}
		if (entry.isDirectory()) {
			entry.close();
			continue;
		}
		client.println("<tr>");
		client.println("<td>" + fileName + "</td>");
		client.println("<td>" + String(entry.size()) + " bytes</td>");
		client.println("</tr>");
		entry.close();
	}
	client.println("</table>");

	client.println("</body>");
	client.println("</html>");
}



// Gestisce le richieste non valide
void handleBadRequest(EthernetClient client) {
	client.println("HTTP/1.1 400 Bad Request");
	client.println("Content-Type: text/html");
	client.println();
	client.println("<html>");
	client.println("<head>");
	client.println("<title>Richiesta non valida</title>");
	client.println("</head>");
	client.println("<body>");
	client.println("<h1>Richiesta non valida</h1>");
	client.println("<p>La richiesta inviata non è valida. Riprova.</p>");
	client.println("</body>");
	client.println("</html>");
	delay(10);
	client.stop();
}
In future when you post a program/sketch can you enclose it between CODE tags using the # button.
It makes your code much more readable and increases the chance that someone will be able to help you.
 
One thing I see is that you use Serial.println but you have not initialised Serial in setup() or anywhere else.

After having initialised Serial using Serial.begin(115200) it might be useful to sprinkle some more Serial.print("... about in order to determine where the code is failing.
 
You might also be interested in looking at QNEthernet.
It seems to have taken over from NativeEthernet and is the place to go for Ethernet connectivity.
 
Using samples included with QNEthernet have worked well here. If you can demonstrate a problem shawn has been responsive.

As for Serial.begin() - it isn't needed as when built with USB Serial it will always start, but not waiting for it may lose early prints. Doing Serial.begin() puts a delay of ~2 seconds before returning, unless it arrives sooner. Putting an overt wait for: while ( !Serial && millis() < 5000 ); will wait for 5 seconds (or less if needed) for example to assure output is ready for transfer.
 
Back
Top