#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
// 請輸入你的 Wi-Fi 資訊
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
// CWA API 金鑰
const String apiKey = "CWA-E674562A-AEDF-49CE-9C9C-A55711FA4476";
// 台中市的地區代碼
const String locationName = "臺中市";
// CWA API 的 URL
const String apiUrl = "https://opendata.cwa.gov.tw/api/v1/rest/datastore/F-C0032-001?Authorization=" + apiKey + "&locationName=" + locationName;
void setup() {
Serial.begin(115200);
WiFi.begin("Wokwi-GUEST", "", 6); //wokwi提供的虛擬 WiFi 接入點
//WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected!");
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(apiUrl); // 設定 API 的 URL
int httpCode = http.GET(); // 發送 GET 請求
if (httpCode > 0) {
String payload = http.getString(); // 取得回應的字串
// 解析 JSON 資料
StaticJsonDocument<1024> doc;
DeserializationError error = deserializeJson(doc, payload);
if (!error) {
// 取得溫度與濕度資料
float temperature = doc["records"]["location"][0]["weatherElement"][2]["time"][0]["parameter"]["parameterName"];
float humidity = doc["records"]["location"][0]["weatherElement"][1]["time"][0]["parameter"]["parameterName"];
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
} else {
Serial.print("JSON parsing failed: ");
Serial.println(error.c_str());
}
} else {
Serial.print("HTTP request failed. Error code: ");
Serial.println(httpCode);
}
http.end(); // 結束 HTTP 連線
}
delay(60000); // 每 60 秒抓取一次資料
}