본문 바로가기

코딩 놀이

서버와 스마트폰

  • 다음 코드를 실행하고, 스마트폰에서 접속해봅니다.

  • 두 기기 모두 같은 공유기에 접속되어 있어야 합니다.

#include <ESP8266WiFi.h> //Wi-Fi 라이브러리로드

const char* ssid     = "IOT22"; // 공유기[네트워크] 명칭(SSID) 
const char* password = "zzz19540410";  // 암호

WiFiServer server(80);  // 포트 번호를 80

String header;
unsigned long currentTime = millis();
unsigned long previousTime = 0; 
const long timeoutTime = 2000;       //2초

void setup() {
  Serial.begin(115200);
  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}

void loop(){
  WiFiClient client = server.available();   

  if (client) {                           
    String currentLine = "";                           
    currentTime = millis();
    previousTime = currentTime;
    while (client.connected() && currentTime - previousTime <= timeoutTime) { 
      currentTime = millis();         
      if (client.available()) {          
        char c = client.read();           
        Serial.write(c);                   
        header += c;
         if (c == '\n') {                  
         if (currentLine.length() == 0) {
             client.println("HTTP/1.1 200 OK"); 
             client.println("Content-type:text/html");
             client.println("Connection: close");
             client.println();
             client.println("<!DOCTYPE html><html>");
             client.println("<head></head>");
             client.println("<body>");
             client.println("<h1>ESP8266 Web Server</h1>");                     
            client.println("</body>");
            client.println("</html>");     
             client.println();       
            break;
          } else {
            currentLine = "";
          }
        } else if (c != '\r') { 
          currentLine += c;    
        }
      }
    }

    header = "";
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}

스마트폰 접속화면

'코딩 놀이' 카테고리의 다른 글

Button(HTML)  (0) 2021.03.08
HTML 언어 구조  (0) 2021.03.07
WiFi 공유기 접속  (0) 2021.03.07
nodeMCU wifi esp8266  (0) 2021.03.06
타이머 카운터와 펄스  (0) 2021.03.05