22.02.25 날씨 정보 Open API

최고고·2022년 2월 25일
0

날씨API정보를 가져와 아두이노 시리얼모니터에 출력

  1. 날씨 정보를 알려주는 open API https://openweathermap.org/api 접속 후 회원가입하고 나의 인증키를 만든다
  2. https://openweathermap.org/current#current_JSON 에서
    에서 JSON으로 돌려받는 방법 찾기->
    api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}
    api.openweathermap.org/data/2.5/weather?q=Gwangju,kr&appid=나의 인증키
  3. 주소창에 요청을 하게 되면 json, xml로 데이터 돌려줌
  4. 받아온 json값을 보기쉽게 http://json.parser.online.fr/ 에 복붙하기



    가장 바깥 중괄호- 그다음 중괄호안에 또 중괄호가 있음 => json안에 json존재
    온도, 습도는 main안의 json데이터 temp, humidity
    풍속은 wind의 speed
#include <ArduinoJson.h>
#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "gogogo2";
const char* password =  "12345678";

String result = "";


void setup() {

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

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }

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

}

void loop() {

  if ((WiFi.status() == WL_CONNECTED)) { //Check the current connection status

    HTTPClient http;

    http.begin("https://api.openweathermap.org/data/2.5/weather?q=Gwangju,kr&appid=71c5405a16380a9e0fef7ad1a0060ccf"); //Specify the URL
    int httpCode = http.GET();                                        //Make the request

    if (httpCode > 0) { //Check for the returning code

      Serial.println(httpCode);
      result = http.getString();
//      Serial.println(result);

      DynamicJsonBuffer jsonBuffer;
      JsonObject& root = jsonBuffer.parseObject(result);
       //result를 형변환해서 jsonBuffer타입으로, 
       //json parsing 사이트에서 변환해서 보면 json안에 json이 있는 경우가 있음
       //root 키 값안에 main이라는 키가 있음, 안에 또 담아주기
      JsonObject& root_main = root["main"];
      //key값은 복사해서 사용하기
//      root_main.printTo(Serial);  //json값을 시리얼모니터로확인만
      double temp = root_main["temp"];  //key값을 담으면 value가 담김
      temp = temp - 273.14;		//절대온도이기때문에 값 빼줘야됨
      Serial.print("현재 기온은 : ");
      Serial.print(temp);
      Serial.println("도 입니다.");
      
      int humidity = root_main["humidity"];
      Serial.print("현재 습도는 : ");
      Serial.print(humidity);
      Serial.println("% 입니다.");
      
      JsonObject& root_wind = root["wind"];
      double wind_speed = root_wind["speed"];
      Serial.print("현재 풍속은 : ");
      Serial.print(wind_speed);
      Serial.println("m/s 입니다.");
      
      
    }
    else {
      Serial.println("Error on HTTP request");
    }

    http.end(); //Free the resources
  }
  delay(1000);
}

0개의 댓글