两种用法
ESP32 作为客户端
向别的服务器发请求,比如拿天气数据、推送消息到手机、调用 AI 接口。最常用。
ESP32 作为服务器
在 ESP32 上跑一个小 Web 服务,手机浏览器访问它的 IP,就能控制继电器开关。
发送 GET 请求
#include <WiFi.h>
#include <HTTPClient.h>
void loop() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin("http://api.example.com/data");
int httpCode = http.GET();
if (httpCode == 200) {
String body = http.getString();
Serial.println(body);
} else {
Serial.print("请求失败,错误码: ");
Serial.println(httpCode);
}
http.end();
}
delay(30000); // 每30秒请求一次
}
ESP32 当小服务器
#include <WiFi.h>
#include <WebServer.h>
WebServer server(80);
void handleRoot() {
server.send(200, "text/html",
"<h1>ESP32 控制台</h1>"
"<a href='/on'>开灯</a> "
"<a href='/off'>关灯</a>");
}
void handleOn() {
digitalWrite(2, HIGH);
server.send(200, "text/plain", "已开灯");
}
void setup() {
pinMode(2, OUTPUT);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) delay(500);
server.on("/", handleRoot);
server.on("/on", handleOn);
server.begin();
Serial.println(WiFi.localIP()); // 打印IP,浏览器访问这个地址
}
void loop() {
server.handleClient();
}