该示例代码使用了 OpenWeatherMap API 来获取天气数据,您需要将代码中的 API 密钥和城市名称替换为您自己的。
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
// Replace with your own API key, obtained from the OpenWeatherMap website.
const char* apiKey = "your_api_key";
// Replace with your city name.
const char* city = "your_city_name";
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Initialize the OLED display using the Adafruit_SSD1306 library.
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire);
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi network.
WiFi.begin("your_network_ssid", "your_network_password");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Wire.begin();
// Initialize the OLED display.
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
// Clear the screen before displaying weather information.
display.clearDisplay();
}
void loop() {
// Make an HTTP request to get the weather forecast data.
HTTPClient http;
String url = "http://api.openweathermap.org/data/2.5/weather?q=";
url += city;
url += "&appid=";
url += apiKey;
url += "&units=metric";
http.begin(url);
int httpResponseCode = http.GET();
if (httpResponseCode == 200) {
String payload = http.getString();
// Parse the JSON response to extract the temperature and weather description.
DynamicJsonDocument doc(1024);
deserializeJson(doc, payload);
const char* temperature = doc["main"]["temp"];
const char* description = doc["weather"][0]["description"];
// Display the weather information on the OLED display.
display.clearDisplay();
display.setCursor(0, 0);
display.setTextSize(1);
display.setTextColor(WHITE);
display.println("Temperature: " + String(temperature) + " C");
display.println("Description: " + String(description));
display.display();
} else {
Serial.println("Error in HTTP request");
}
// Wait for one minute before making another request.
delay(60000);
}