ESP-C3-32S-KIT 开发板使用 I2C 协议连接 0.96寸 OLED 并显示天气预报

该示例代码使用了 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);
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值