ESP32 - Webserver
Voir ESP32 - HTTPClient
J'ai la flemme d'écrire comment ca marche. Je crois que le code est assez simple/clair. En gros, on lance un hotspot WiFi puis un serveur HTTP qui renvoie une petit page web "Hello world".
Hotspot WiFi
#include <WiFi.h>
const char* ssid = "ESP32";
const char* password = "12345678";
IPAddress local_ip(192,168,1,1);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);
void setup() {
WiFi.softAPConfig(local_ip, gateway, subnet);
WiFi.softAP(ssid, password);
}
Server HTTP
#include <WebServer.h>
Objet Webserver:
WebServer server(80);
Fonction d'envoi d'une page HTML: (syntaxe texte multiligne -> https://davidmac.pro/posts/2024-12-07-arduino-cpp-multiline-strings/)
void handleRoot() {
String html = R"HTML(
<!DOCTYPE html>
<html>
<head>
<title>Server ESP32</title>
</head>
<body>
<h1>Hello world !</h1>
</body>
</html>
)HTML";
server.send(200, "text/html", html);
}
Dans setup
, on défini les actions a exécuter par le serveur puis on lance le serveur:
void setup() {
server.on("/", handleRoot);
server.onNotFound([]() {
server.send(404, "text/plain", "Not Found");
});
server.begin();
}
void loop(void) {
server.handleClient();
}
Le code
#include <WiFi.h>
#include <WebServer.h>
// put connection informations here
const char* ssid = "ESP32";
const char* password = "12345678";
IPAddress local_ip(192,168,1,1);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);
WebServer server(80);
void handleRoot() {
String html = R"HTML(
<!DOCTYPE html>
<html>
<head>
<title>Server ESP32</title>
</head>
<body>
<h1>Hello world !</h1>
</body>
</html>
)HTML";
server.send(200, "text/html", html);
}
void setup() {
Serial.begin(115200);
while (!Serial) continue;
WiFi.softAPConfig(local_ip, gateway, subnet);
WiFi.softAP(ssid, password);
Serial.println(WiFi.softAPIP());
server.on("/", handleRoot);
server.onNotFound([]() {
server.send(404, "text/plain", "Not Found");
});
server.begin();
Serial.println("HTTP server started");
}
void loop(void) {
server.handleClient();
}