ESP8266制作天气预报显示屏(接入OpenWeatherMap API)

2025-06发布3次浏览

制作一个基于ESP8266的天气预报显示屏,接入OpenWeatherMap API是一个非常有趣的项目。这不仅可以帮助你了解如何使用微控制器与互联网服务交互,还能深入学习硬件控制和数据解析技术。

以下是如何实现这一项目的详细步骤:

1. 硬件准备

  • ESP8266模块:可以使用NodeMCU开发板。
  • OLED显示屏:如0.96寸I2C接口OLED屏幕。
  • 面包板和杜邦线:用于连接电路。
  • 电源:5V USB供电即可满足需求。

2. 软件准备

  • Arduino IDE:用于编写代码并上传到ESP8266。
  • OpenWeatherMap API:注册账号获取API Key。
  • WiFi网络:确保ESP8266能连接到你的WiFi。

3. 连接硬件

将ESP8266与OLED显示屏通过I2C协议连接起来。具体接法如下:

  • OLED的SCL接到ESP8266的D1 (GPIO5)。
  • OLED的SDA接到ESP8266的D2 (GPIO4)。
  • OLED的VCC和GND分别接到ESP8266的5V和GND。

4. 安装必要库

在Arduino IDE中安装以下库:

  • Adafruit_SSD1306:用于驱动OLED显示屏。
  • Wire:支持I2C通信。
  • WiFiClientSecure:用于HTTPS请求。
  • ArduinoJson:用于解析JSON格式的数据。

5. 编写代码

初始化WiFi连接

#include <ESP8266WiFi.h>
const char* ssid = "your_ssid";
const char* password = "your_password";

void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

获取天气数据

#include <ESP8266HTTPClient.h>
const char* api_key = "your_api_key";
const char* city = "Beijing";

String getWeatherData() {
  String url = "http://api.openweathermap.org/data/2.5/weather?q=" + String(city) + "&appid=" + String(api_key) + "&units=metric";
  HTTPClient http;
  http.begin(url);
  int httpResponseCode = http.GET();

  if (httpResponseCode > 0) {
    String payload = http.getString();
    return payload;
  } else {
    Serial.print("Error on sending GET: ");
    Serial.println(httpResponseCode);
  }
  http.end();
  return "";
}

解析JSON数据

#include <ArduinoJson.h>

float parseTemperature(String jsonData) {
  StaticJsonDocument<200> doc;
  deserializeJson(doc, jsonData);
  float temperature = doc["main"]["temp"];
  return temperature;
}

显示温度到OLED

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

void displayTemperature(float temp) {
  display.clearDisplay();
  display.setTextSize(2);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.print("Temp: ");
  display.print(temp);
  display.print(" C");
  display.display();
}

void loop() {
  String weatherData = getWeatherData();
  float temperature = parseTemperature(weatherData);
  displayTemperature(temperature);
  delay(60000); // Update every minute
}

6. Mermaid流程图

sequenceDiagram
  participant ESP8266
  participant OpenWeatherMap
  participant OLED
  
  ESP8266->>OpenWeatherMap: 发送HTTP请求
  OpenWeatherMap-->>ESP8266: 返回JSON数据
  ESP8266->>ESP8266: 解析JSON数据
  ESP8266->>OLED: 显示温度

结束语

通过以上步骤,你可以成功地制作一个基于ESP8266的天气预报显示屏。这个项目不仅展示了物联网设备的强大功能,还提供了一个很好的实践机会来学习嵌入式系统编程和网络编程。