|
|
在心知天氣網站上注冊登陸獲取一個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); 關機
}
|
評分
-
查看全部評分
|