esp8266天气时钟arduino代码
时间: 2023-09-08 07:10:18 浏览: 171
以下是使用ESP8266制作天气时钟的Arduino代码示例:
```c
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
#include <Time.h>
#include <TimeLib.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// Replace with your network credentials
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// Replace with your city and API key
const char* city = "your_city";
const char* apiKey = "your_API_key";
// OLED display
#define OLED_RESET 0
Adafruit_SSD1306 display(OLED_RESET);
void setup() {
Serial.begin(115200);
delay(1000);
// OLED display setup
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.println("Weather Clock");
display.display();
delay(2000);
display.clearDisplay();
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi!");
// Initialize time
configTime(0, 0, "pool.ntp.org");
while (!time(nullptr)) {
delay(1000);
Serial.println("Fetching NTP time...");
}
Serial.println("NTP time fetched!");
}
void loop() {
// Connect to OpenWeatherMap API
HTTPClient http;
String apiUrl = "http://api.openweathermap.org/data/2.5/weather?q=" + String(city) + "&appid=" + String(apiKey);
http.begin(apiUrl);
int httpCode = http.GET();
if (httpCode > 0) {
String response = http.getString();
// Parse JSON response
DynamicJsonDocument doc(1024);
deserializeJson(doc, response);
JsonObject weather = doc["weather"][0];
JsonObject main = doc["main"];
String description = weather["description"];
float temperature = main["temp"];
int humidity = main["humidity"];
// Display data on OLED display
display.clearDisplay();
display.setCursor(0,0);
display.println("City: " + String(city));
display.println("Date: " + String(day()) + "/" + String(month()) + "/" + String(year()));
display.println("Time: " + String(hour()) + ":" + String(minute()) + ":" + String(second()));
display.println("Temperature: " + String(temperature) + " C");
display.println("Humidity: " + String(humidity) + " %");
display.println("Description: " + description);
display.display();
}
else {
Serial.println("Error connecting to OpenWeatherMap API!");
}
http.end();
// Wait for 1 minute before updating data
delay(60000);
}
```
请注意,您需要将代码中的以下部分替换为您自己的网络凭据和OpenWeatherMap API密钥:
```c
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* city = "your_city";
const char* apiKey = "your_API_key";
```
此外,您还需要将Adafruit_SSD1306库和ArduinoJson库添加到您的Arduino IDE中。
阅读全文