본문 바로가기
...

[ESP-8266 가지고 놀기 Ep.2] WiFi 연결 및 웹페이지 생성

by GGoris 2022. 3. 25.
반응형

esp-8266 은 wifi 모듈로 주변 wifi에 연결 가능하다.

이에 필요한 라이브러리들이 몇가지 필요하다.

 

 

https://github.com/me-no-dev/ESPAsyncWebServer

 

GitHub - me-no-dev/ESPAsyncWebServer: Async Web Server for ESP8266 and ESP32

Async Web Server for ESP8266 and ESP32. Contribute to me-no-dev/ESPAsyncWebServer development by creating an account on GitHub.

github.com

 

 

위 링크에서 Zip파일로 다운로드한다.

 

외부 라이브러리를 추가하기 위해서는

스캐치->라이브러리 포함하기->.ZIP 라이브러리추가...

를 선택한다.

파일선택창에서 다운로드 받은 파일을 선택한다.

 

이후 다시 

스케치->라이브러리 포함하기

에 보면 추가 된 것을 확인할 수 있다.

 

 

이후 아래와 같이 코드를 작성한 후,

#include <ESPAsyncWebServer.h>
#include <ESP8266WiFi.h>

const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html>
  <body>
    <center>
      <h1>WiFi Web Test Page</h1><br>
      <hr>
        <a href="https://wowan.tistory.com">wowan.tistory.com</a>
    </center>
  </body>
</html>
)rawliteral";

#define PORT 8266 //외부접속을 위한 포트
IPAddress local_IP(192, 168, 0, ***);  //고정 IP를 위한 ip값
IPAddress gateway(192, 168, 1, 1);  //게이트웨이
IPAddress subnet(255, 255, 0, 0);  //넷마스크

//고정ip와 포트를 사용하면 공유기 포트포워딩 및 DDNS를 통해 외부접속이 가능!


const char* ssid     = "your-wifi-name";  //와이파이 이름
const char* password = "wifi-password";  // 비밀번호


AsyncWebServer server(PORT); 

//잘못된 경로로 접속했을 때 보여줄 페이지도 작성할 수 있다.
void notFound(AsyncWebServerRequest *request) {
  request->send(404, "text/plain", "Not found");
}


void setup() {
  Serial.begin(9600); //시리얼통신 비트레이트 설정.
  Serial.println("Start Setup");
  
  //WiFi 연결정보 설정
  if (!WiFi.config(local_IP, gateway, subnet)) {
    Serial.println("STA Failed to configure");
  }
  
  //WiFi 연결 시도
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  //루트페이지 연결
  server.on("/", [] (AsyncWebServerRequest *request){
    Serial.println("You called root page");
    request->send_P(200, "text/html", index_html); //Send web page
  });

  //NotFound페이지 연결
  server.onNotFound(notFound);
  server.begin();
}

void loop(){
  
}

업로드 고고!

 

작성했던 ip주소로접속을 하면!

성공!

반응형

댓글