ESP32網頁伺服器控制LED
ESP32網頁伺服器控制LED
前面一樣的就不再重覆紀錄,添加這一節相關的部份
主要是就加了網頁給客戶端請求動作的部份
void ledOn(){
digitalWrite(led, HIGH);
server.send(200, "text/html; charset=UTF-8", "LED已開啓<br>\
<a href=/off>關閉LED</a>");
}
void ledOff(){
digitalWrite(led, LOW);
server.send(200, "text/html; charset=UTF-8", "LED已關閉<br>\
<a href=/on>開啓LED</a>");
}
完整程式碼
#include <WiFi.h>
#include <WebServer.h>
const char *ssid="基地台名稱";
const char *password="基地台密碼";
WebServer server(80);
const int led=2;
void handleRoot(){
String html = "<a href=\"/on\">開啓LED</a>";
html +="<br>";
html +="<a href=\"/off\">開閉LED</a>";
server.send(200, "text/html; charset=UTF-8", html);
}
void handleNotFound(){
server.send(400, "text/html; charset=UTF-8", "找不到回傳的訊息");
}
void ledOn(){
digitalWrite(led, HIGH);
server.send(200, "text/html; charset=UTF-8", "LED已開啓<br>\
<a href=/off>關閉LED</a>");
}
void ledOff(){
digitalWrite(led, LOW);
server.send(200, "text/html; charset=UTF-8", "LED已關閉<br>\
<a href=/on>開啓LED</a>");
}
void setup(void){
Serial.begin(115200);
pinMode(led, OUTPUT);
WiFi.begin(ssid, password);
server.begin();
while (WiFi.status() != WL_CONNECTED){
Serial.print(".");
delay(500);
}
Serial.print("已連線至基地台");
Serial.println(ssid);
Serial.print("請於瀏覽器中開啓這個IP位址: ");
Serial.println(WiFi.localIP());
server.on("/", handleRoot);
server.onNotFound(handleNotFound);
Serial.println("HTTP伺服器已啓動");
server.on("/on", ledOn);
server.on("/off", ledOff);
}
void loop() {
server.handleClient();
}
留言
張貼留言