ESP8266 서버, 클라이언트 - ESP8266 seobeo, keullaieonteu

낙서장

2개의 ESP8266모듈을 서버, 클라이언트로 접속시켜 서로 통신하기

2개의 ESP8266모듈을 서버, 클라이언트로 접속시켜 서로 통신하기

기기들간에 데이터를 무선으로 주고 받으려면 여러가지 방법이 있을 수 있습니다. 

- 먼저 여러 지난 포스트에서 처럼, MQTT 프로토콜과 같은 브로커 (서버)를 두고 다수의 여러 클라이언트들끼리 통신하는 방법,

- 중간에 WiFi공유기를 두고 다수의 WiFi기기들이 서로 통신하는 방법,

- RF 송신기, 수신기를 사용하여 1:1로 통신하는 방법,

- 적외선 또는 블루투스를 사용하여 1:1로 통신하는 방법.

ESP8266 두개를 준비하여, 하나는 서버로 또 다른 하나는 클라이언트로 접속하면 구성이 간단하고 ESP8266 두개 이외의 장비는 필요 없다는 장점이 있습니다.  물론 WiFi 범위를 벗어나면 통신이 끊기겠지만, 인터넷도, 공유기도 필요없이 간단하고 저렴하게 기기간의 통신이 가능합니다.

아래와 같은 순서로 프로그래밍을 해보겠습니다.

1. 두개의 ESP8266을 준비하고, 하나를 서버로, 다른 하나를 클라이언트로 서로 접속합니다.

2. 클라이언트 ESP8266에서 서버 ESP8266으로 HTTP request를 보내어, 서버 ESP8266이 루트에 특정 정보를 표시하고 (ESP8266의 경우 192.168. 4. 1),  클라이언트에 답신을 하도록 합니다.

3.  클라이언트 ESP8266에서는 전송된 정보를 받아 표시합니다.

참고: ESP8266에서는 비밀번호를 짧게 설정하거나 SSID가 너무 길면 SSID가 바뀌지 않습니다.

서버쪽 ESP8266 프로그램

서버쪽 ESP8266에서는 SSID를 "ESP_Communication_Test" 접속 비밀번호를 "12345678"로 설정하여 AP모드로 작동합니다.

i값을 계속 증가시키다가, 아래 클라이언트 ESP8266이 접속 되어 HTTP 호출을 하거나, 핸드폰의 인터넷브라우저나, 컴퓨터의 인터넷브라우저로 192.168.4.1를 호출하면 루트페이지에 메시지를 표시하고, 동일한 메세지를 클라이언트로 전송합니다.


#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <WiFiServer.h>
#include <ESP8266WebServer.h>
const char* ssid="ESP_Communication_Test";  // SSID of esp8266
const char* password="12345678";  
int i=0;
ESP8266WebServer server(80);    //Specify port for TCP connection

void handleRoot() {
  String s = "\r\n\r\n<!DOCTYPE HTML>\r\n<html><h2>Two ESP8266 Communication Test</h2>";
        s += "<p>Success!!!</p>";
        s += "<p>"+String(i)+"</p>";
        s += "</html>\r\n\r\n"; 
  server.send(200,"text/html",s);      //Reply to the client
}

void setup() {
  delay(200);                          
  Serial.begin(9600);                 //Set Baud Rate
  WiFi.softAP(ssid,password);      //In Access Point Mode
  IPAddress myIP=WiFi.softAPIP();     //Check the IP assigned. Put this Ip in the client host.
  Serial.print("AP IP address: ");
  Serial.println(myIP);                 //Print the esp8266-01 IP(Client must also be on the save IP series)
  server.on("/",handleRoot);           //Checking client connection
  server.begin();                       // Start the server
  Serial.println("Server started");
}

void loop() {
  server.handleClient();
  i=i+1;
}

클라이언트쪽 ESP8266 프로그램

SSID가 "ESP_Communication_Test"인 AP에 비밀번호를 "12345678"로 하여 접속합니다.  접속이 성공하면 192.168.4.1에 접속하여 HTTP get 요청을하여 페이지의 내용을 line 문자변수에 저장하여 serial 모니터에 표시합니다.  HTTP 요청이 수락된 이후에는 192.168.4.1 접속이 종료되므로 ("ESP_Communication_Test"인 AP에는 접속을 유지합니다만) 5초 후 다시 접속하여 HTTP 요청을 반복합니다. 


#include <ESP8266WiFi.h>
#include <WiFiClient.h>
const char* host="192.168.4.1"; //Its the ip of the esp8266 as Access point
const char* ssid="ESP_Communication_Test";
const char* password="12345678"; 
const int httpPort=80;
String line="";

void setup() {
  Serial.begin(9600);  
  WiFi.mode(WIFI_STA);    
  WiFi.begin(ssid, password);      //Connect to the server ESP8266
  while (WiFi.status() != WL_CONNECTED) {      
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected"); 
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());          
}

void loop() {
   Serial.print("connecting to ");
   Serial.println(host);
   WiFiClient client; // Use WiFiClient class to create TCP connections
   if (!client.connect(host, httpPort)) {
      Serial.println("connection failed");
      return;
   }   
   client.print(String("GET ")+"/"+" HTTP/1.1\r\n"+"Host: "+host+"\r\n"+"Connection: close\r\n\r\n"); //Request to server   
   delay(10);
   while(client.available()){
      String line = client.readStringUntil('\r'); // Read all the lines of the reply from server                
      Serial.println(line);
   }
   Serial.println("closing connection");            
   delay(5000);
}

클라이언트 ESP8266의 시리얼모니터에서는 아래와 같이 표시가 됩니다.

Toplist

최신 우편물

태그