醬是創客的ESP32教學主題第六篇,以Ai-Thinker安信可NodeMCU-32S(使用Arduino語言)來實作教學,本篇教學將著重於建立Web Server做一個HTML客製化網頁頁面,讓Wifi用戶連入修改資料,用戶透過WiFi連到ESP32,本篇以簡易的HTML的輸入框和Submit按鈕,並透過get的方式跳轉設定參數到ESP32上

以下是我們今天的目標

  • ESP32開發板連線至無線網路基地台iot/chosemaker
  • 使用WebServer.h函數
  • HTML的基本用法
  • 網址 IP/uid 為設定User ID區域,並拉一個輸入框和Submit按鈕,並跳轉至/setuid
  • 如何取得get的User ID值

設備:
安信可NodeMCU-32S #露天拍賣 #蝦皮購物

Arduino 範例程式碼如下

//醬是創客 開發實作的好夥伴
#include "WiFi.h"
#include <WebServer.h>
//輸入你的SSID/password
String write_ssid = "iot";
String write_password = "chosemaker";
int statusCode;
String content;
String room_id = "";
//宣告webserver
WebServer server(80);
 
void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, passphrase);
  if (testWifi()) {
    Serial.println("WiFi connected OK");
    Serial.print("Local IP: ");
    Serial.println(WiFi.localIP());
    //設定webserver
    createWebServer();
    server.begin();
    Serial.println("Server started");
  }
  else {
    Serial.println("WiFi connected NG");
  }
   
}
 
void loop() {
  //handleClient要放在loop
   server.handleClient();
}
 
bool testWifi(void) {
  int c = 0;
  Serial.println("Waiting for Wifi to connect");
  while ( c < 20 ) {
    if (WiFi.status() == WL_CONNECTED) { return true; }
    delay(500);
    Serial.print(WiFi.status());  
    c++;
  }
  return false;
}

void createWebServer()
{

    server.on("/uid", []() {

        content = "<!DOCTYPE HTML>\r\n<html>";
        content += "<p>";
        content += "<ol>";
        content += room_id;
        content += "</ol>";
        content += "</p><form method='get' action='setuid'><label>UID</label><input name='uid' length=64><input type='submit'></form>";
        content += "</html>";
        server.send(200, "text/html", content);
    });

    server.on("/setuid", []() {
        room_id = server.arg("uid");    
        if (room_id.length() > 0) {
          Serial.println("html uid:");
          Serial.println(room_id);
          content = "{\"Success\"}";
          statusCode = 200;
        } else {
          content = "{\"Error\":\"404 not found\"}";
          statusCode = 404;
          Serial.println("Sending 404");
        }
        server.send(statusCode, "application/json", content);
    });

}

瀏覽器 輸出如下,首先我們知道IP為192.168.2.105,請先打192.168.2.105/uid,並輸入chosemaker按提交,之後再refresh 192.168.2.105/uid網頁一次,就可以出現你的輸入值

Arduino 序列埠監控視窗 輸出如下

Waiting for Wifi to connect
03WiFi connected OK
Local IP: 192.168.2.105
Server started
html uid:
chosemaker