상세 컨텐츠

본문 제목

WiFiManger web server 코드 와 html 문서 처리

IoT

by 폴리프레임 2025. 5. 15. 13:12

본문

반응형

index.h

const char index_html[] PROGMEM = R"rawliteral(<html>...</html>)rawliteral";

 

esp32_wm_server.ino

#include <WiFiManager.h>
#include <ESPAsyncWebServer.h>
#include <DNSServer.h>
#include <ESPmDNS.h>
#include <Update.h>

#include "index.h"

const char* http_username = "username"; // 웾 접속 용
const char* http_password = "password"; // 웹 접속 용

AsyncWebServer server(80);    // Create an instance of the AsyncWebServer

int nCounter;

void notFound(AsyncWebServerRequest *request) {
  request->send(404, "text/plain", "Not found");
}

void setup() {
    pinMode(LED_BUILTIN, OUTPUT);

    WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP

    // put your setup code here, to run once:
    Serial.begin(115200);
    
    //WiFiManager, Local intialization. Once its business is done, there is no need to keep it around
    WiFiManager wm;
    //wm.resetSettings();

    bool res;
    // res = wm.autoConnect(); // auto generated AP name from chipid
    // res = wm.autoConnect("AutoConnectAP"); // anonymous ap
    res = wm.autoConnect("AutoConnectAP","password"); // password protected ap

    if(!res) {
        Serial.println("Failed to connect");
        // ESP.restart();
    } 
    else {
        Serial.println("connected...yeey :)");
    }

    server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
    if (!request->authenticate(http_username, http_password))
      return request->requestAuthentication();
    request->send_P(200, "text/html", index_html, NULL);
  });
  
    server.on("/adc_value", HTTP_GET, [](AsyncWebServerRequest * request) {
    nCounter ++;
    request->send(200, "text/html", String(nCounter));
  });

      server.on("/led_toggle", HTTP_GET, [](AsyncWebServerRequest * request) {
    Serial.println("LED Toggled!!!");
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    request->send(200, "text/html", "");
  });

  server.on("/get", HTTP_GET, [] (AsyncWebServerRequest * request) {
    String inputMessage;
    String inputParam;

    Serial.println(inputMessage);
    request->send(200, "text/html", index_html);
  });
  server.onNotFound(notFound);
  server.begin();
}

void loop() {

}

 

 

  • const char index_html[] : index.html은 문자열 배열호 선언되었음. 이를 통해 HTML 코드가 저장되었음
  • PROGRAM : PROGMEM은 AVR 기반 마이크로컨트롤러(예: ESP8266, ESP32)에서 플래시 메모리에 데이터를 저장하도록 하는 키워드입니다. 기본적으로 문자열은 RAM에 저장되지만, PROGMEM을 사용하면 플래시 메모리에 저장되어 RAM 사용량을 줄일 수 있습니다. esp32 에는 RAM(SRAM)은 320KB~520KB 제공, Flash Memory는 4 MB ~ 1MB 제공
  • R"rawliteral(...)"rawliteral" : Raw String Literal이라는 문법입니다. 일반적으로 문자열을 정의할 때 "문자열"처럼 따옴표를 사용하지만, HTML 코드에는 "나 \ 같은 특수문자가 많아 이스케이프(escape) 처리가 필요합니다. 그러나, R"rawliteral(...)rawliteral"을 사용하면 HTML 코드를 그대로 저장할 수 있어 가독성이 높아집니다.