Project/Arduino

Esp32로 웹서버 통신(http POST, Json 형식)

Juzero 2020. 5. 28. 10:48

영단어 퀴즈 앱테크 어플 (하루 5분 100원 적립 가능!)

아이폰>

 

‎캐시보카 - 돈버는 영단어 앱테크

‎단어를 맞추면 1캐시가 적립돼요. 적립된 캐시는 네이버 포인트로 전환할 수 있어요.

apps.apple.com

 

 

esp32의 예제가 많이 없어서 찾기 힘들었다.

 

본 코드는 esp32에 있는 값을 POST 방식을 통해 Json 형태로 웹서버에 보내는 방법이다.

 

http POST를 이용해서 데이터를 보내는 부분만 있다. 우리 팀은 웹서버에서 데이터를 수신할 필요는 없어서 수신 코드는 넣지 않았다. 그리고 본 게시글 하단에 참조된 사이트에 GET 방식도 있으니 참조하면 좋을 것 같다. 

 

우리 팀은 AWS에서 프리티어로 웹서버를 개설하고 DB를 구축해놓았다.

 

ESP32 예제가 일단 많이 없을 뿐더러 Http POST 방식에다 Json 형태는 더더욱 없다..

우리도 외국 사이트 헤매면서 겨우겨우 찾아냈다... 

 

#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <HttpClient.h>
 
const char* ssid = "juzeor";    //wift 아이디
const char* password =  "space!";    // wifi 비번 
const char* serverName = "http://00.000.00.00:0000"; // 웹서버주소
int value;
int sensor_number = 12;  // 임의의 숫자를 넣어주었다. 
int analog = 25;  // esp에 연결된 핀 번호

IPAddress hostIp(00, 000, 00, 00);  //웹서버의 ip 주소
int SERVER_PORT = 5000;  // 웹서버 포트 번호
WiFiClient client;

void setup() {
 
  Serial.begin(115200);

  WiFi.begin(ssid, password);   // 와이파이 접속
 
  while (WiFi.status() != WL_CONNECTED) { //Check for the connection
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }
 
  Serial.println("Connected to the WiFi network");
 
}
 
void loop() {
 
 if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status
     
     value = analogRead(analog); // esp32에서 읽은 co2 값을 value에 저장한다.
     HTTPClient http;   
   
     http.begin("http://00.000.00.00:5000/");  //Specify destination for HTTP request
     http.addHeader("Content-Type",  "application/x-www-form-urlencoded");   //Specify content-type header,  Json형식의 타입이다.
  
     String httpRequestData = "sensor_number="+String(sensor_number)+"&value="+String(value);  // 가장 중요한 Json 데이터를 입력하는 부분이다  = 의 왼쪽이 key값 오른쪽이 value 값이고 &를 기준으로 쌍이 나뉘어진다.
     Serial.println(httpRequestData); //시리얼 모니터에 Json 형식의 데이터를 찍어준다.
     int httpResponseCode = http.POST(httpRequestData);   //Send the actual POST request
   
     if(httpResponseCode>0){ // 잘 전송되었으면
  
      String response = http.getString();                       //Get the response to the request
   
      Serial.println(httpResponseCode);   //Print return code
      Serial.println(response);           //Print request answer
   
     }else{
   
      Serial.print("Error on sending POST: ");
      Serial.println(httpResponseCode);
   
     }
   
     http.end();  //Free resources
   
 }else{

    Serial.println("Error in WiFi connection");   
 }
 
  delay(30000000);  //Send a request every 10 seconds
 
}

 

라이브러리는 아두이노 보드매니저에서 찾으면 있으니 설치해서 include 시켜주면 된다. 

 

위에 코드에서 본인이 바꾸어야 할 것들

 

Wifi id

Wifi password

웹서버의 Ip, Port 번호

아날로그 핀 번호  등등

 

https://randomnerdtutorials.com/esp32-http-get-post-arduino/

 

ESP32 HTTP GET and HTTP POST with Arduino IDE | Random Nerd Tutorials

Learn how to make HTTP GET and HTTP POST Requests with the ESP32 board with Arduino IDE. How to get values, post JSON data objects, URL encoded requests, etc.

randomnerdtutorials.com

 

이 사이트에서 나오는 ESP32와 POST 방식의 코드를 참조했다. GET방식도 있으니 사이트를 참조해서 하면 될 것 같다.

 

 


앱 홍보

RN로 만든 주식, 코인 물타기 계산기, 수익률 계산기 앱

안드로이드>

아이폰>

 

UN인턴이 만든 영단어 퀴즈앱

안드로이드>

아이폰>