|
|
在心知天气网站上注册登陆获取一个API后就可利用8266开发板制做一个实时天气数据显示器,显示器右侧有一个按钮,按下一次就可显示室外当前天气状况30秒钟然后自动关机。该显示器还加装了一个DHT11温湿度传感器用于显示当前室内温湿度。下面提供了显示器图片及电路图和程序。
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <ArduinoJson.h>
#include <Wire.h>
#include <SPI.h>
#include <dht11.h>
#include <Arduino.h>
#include <U8g2lib.h>
const char* ssid = "。。。。。。"; //WIFI名称
const char* password = "。。。。。。"; //WIFI密码
const char* host = "api.seniverse com";
String apiKey = "。。。。。。"; // 注册后获取
String location = "shanghai"; // 城市标识
String unit = "c"; // 摄氏度
//U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); //使用OLED显示
U8G2_ST7920_128X64_F_SW_SPI u8g2(U8G2_R0, /* clock=*/ 0, /* data=*/ 2, /* CS=*/ 1, /* reset=*/ 16); //使用ST7920显示
dht11 DHT11;
#define DHT11PIN 14
void setup() {
u8g2.begin(); // 初始化OLED
u8g2.enableUTF8Print(); // 启用UTF-8中文打印
Serial.begin(9600);
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
// WiFi连接
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
u8g2.clearBuffer(); // 清显存
u8g2.setFont(u8g2_font_wqy16_t_gb2312);
u8g2.setCursor(20, 40); // 坐标(x,y),y是基线位置
u8g2.print("心 知 天 气"); // UTF-8中文
u8g2.sendBuffer(); // 显存数据推送到显示器显示
}
}
void loop() {
WiFiClient client;
HTTPClient http;
// 构建API请求URL
String url = "http://" + String(host) + "/v3/weather/now.json?key=" + apiKey +
"&location=" + location + "&language=zh-Hans&unit=" + unit;
// Serial.print("Request URL: ");
// Serial.println(url);
if(http.begin(client, url)) {
int httpCode=http.GET();
String payload=http.getString();
// Serial.println("Payload: " + payload);
// 解析JSON
StaticJsonDocument<200> doc;
DeserializationError error=deserializeJson(doc, payload);
String weather=doc["results"][0]["now"]["text"].as<String>();
int temp=doc["results"][0]["now"]["temperature"].as<float>();
int windSpeed=doc["results"][0]["now"]["wind_speed"];
const char* windDir=doc["results"][0]["now"]["wind_direction"];
float f= windSpeed/3.6;
int chk = DHT11.read(DHT11PIN);
int t= (float)DHT11.temperature;
int h=(float)DHT11.humidity;
u8g2.clearBuffer(); // 清显存
// 设置字体(必须选支持中文的字体,这里用u8g2_font_wqy12_t_gb2312)
u8g2.setFont(u8g2_font_wqy12_t_gb2312);
u8g2.setCursor(0, 20);
u8g2.print("室内;");
u8g2.setCursor(38, 20);
u8g2.print(t);
u8g2.setCursor(56, 20);
u8g2.print("C");
u8g2.setCursor(68, 20);
u8g2.print("湿度:");
u8g2.setCursor(106, 20);
u8g2.print(h);
u8g2.setCursor(122, 20);
u8g2.print("%");
u8g2.setCursor(0, 40);
u8g2.print("温度:");
u8g2.setCursor(38, 40);
u8g2.print(temp);
u8g2.setCursor(56, 40);
u8g2.print("C");
u8g2.setCursor(68, 40);
u8g2.print("天气:");
u8g2.setCursor(106, 40);
u8g2.print(weather);
u8g2.setCursor(0, 60);
u8g2.print("风向:");
u8g2.setCursor(38, 60);
u8g2.print(windDir);
u8g2.setCursor(68, 60);
u8g2.print("风速:");
u8g2.setCursor(106, 60);
u8g2.print(f,1);
u8g2.sendBuffer();
http.end();
} else {
// Serial.println("HTTP begin failed");
}
delay(30000);
digitalWrite(13, LOW); 关机
}
|
评分
-
查看全部评分
|