#include <Wire.h>
#include <WiFi.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <TM1637Display.h>
#include <DHT.h>
// WiFi配置
const char *ssid = "Wokwi-GUEST";
const char *password = "";
// TM1637配置
#define CLK_PIN 4 // 连接到TM1637的CLK引脚
#define DIO_PIN 5 // 连接到TM1637的DIO引脚
TM1637Display tm1637(CLK_PIN, DIO_PIN);
// OLED屏幕配置
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
#define SCREEN_ADDRESS 0x3C
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// DHT22配置
#define DHT_PIN 2
DHT dht(DHT_PIN, DHT22);
void setup() {
Serial.begin(115200);
// 连接到WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// 初始化TM1637
tm1637.setBrightness(0x0f);
// 初始化OLED屏幕
if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
display.display(); // 显示欢迎信息
delay(2000);
display.clearDisplay();
}
void loop() {
// 获取网络时间
configTime(8 * 3600, 0, "pool.ntp.org", "time.nist.gov");
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
Serial.println("Failed to obtain time");
return;
}
// 显示时间在TM1637上
int hour = timeinfo.tm_hour;
int minute = timeinfo.tm_min;
tm1637.showNumberDec(hour * 100 + minute, true);
delay(1000);
// 获取温湿度
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// 显示温度和湿度在OLED上,上下显示
display.setTextSize(3);
display.setTextColor(SSD1306_WHITE);
int x = (SCREEN_WIDTH - 4 * 16) / 2; // 居中
int y = (SCREEN_HEIGHT - 2 * 16) / 2; // 垂直居中
display.setCursor(x, y);
display.print(String(temperature, 1) + " C");
y += 30; // 调整为更大的间距
display.setCursor(x, y);
display.print(String(humidity, 1) + " %");
display.display(); // 刷新OLED屏幕
delay(2000); // 2秒更新一次
display.clearDisplay(); // 清空显示内容
}