Arduino와 SpringBoot를 사용한 온습도 측정 사이트(3) - Arduino편

2024. 6. 14. 11:56Spring-Project

 

이전글 : https://codepracticeroom.tistory.com/199

 

 

이번에는 온습도 데이터를 JSON으로 변환 후 내 localhost에 보내는 것을 한다.

이번 코드는 이전에 했던 wifi연결과 DHT22를 바로 합치고 시작한다.

 

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <DHT.h>
#include <ArduinoJson.h>

#define DHTPIN 5
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

const char* ssid = "ASUS 2.4G";
const char* password = "asus245g";

void setup () {

  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(1000);
    Serial.println("Connecting to WiFi..");

  }
  Serial.println("Connected to the WiFi network");

  dht.begin();
  
}

void loop() {

  delay(10000);					// 10초마다

  float h = dht.readHumidity();
  float t = dht.readTemperature();

  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  if(WiFi.status()== WL_CONNECTED) {

    WiFiClient client;
    HTTPClient http;  

    http.begin(client, "http://192.168.50.236:8080/home");  
    http.addHeader("Content-Type", "application/json");

    DynamicJsonDocument doc(1024);
    doc["temperature"] = t;			// 온도json
    doc["humidity"] = h;			// 습도json

    String httpRequestData;
    serializeJson(doc, httpRequestData);

    int httpResponseCode = http.POST(httpRequestData);   // post로 보냄

    if (httpResponseCode>0) {
      Serial.print("HTTP Response code: ");		
      Serial.println(httpResponseCode);
    }
    else {
      Serial.print("Error code: ");		// 에러가 발생하면
      Serial.println(httpResponseCode);	// 에러코드
    }
    
    http.end();
    
  }
  else {
    Serial.println("WiFi Disconnected");
  }
}

 

 

10초마다 내 localhost 에 온도와 습도 데이터를 json 형태로 보내는 코드이다.

 

 

다음 글에서 온습도 데이터가 정상적으로 들어오는지 테스트를 한다.