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

#define SCREEN_WIDTH 128  // 定义屏幕宽度为128像素 Define the screen width to be 128 pixels
#define SCREEN_HEIGHT 64  // 定义屏幕高度为64像素 Define the screen height to be 64 pixels
#define OLED_RESET -1     // 定义 OLED 复位引脚为-1（如果不使用复位功能，则设置为-1） Define the OLED reset pin to -1 (or -1 if the reset function is not used)
// 创建 Adafruit_SSD1306 对象，用于控制 OLED 屏幕，指定屏幕宽度、高度、I2C 总线对象和复位引脚
// Create an Adafruit_SSD1306 object that controls the OLED screen, specifying the screen width, height, I2C bus object, and reset pin
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

#define DHTPIN 4           // DHT11传感器连接到Arduino的数字引脚4 The DHT11 sensor is connected to digital pin 4 of the Arduino
#define DHTTYPE DHT11      // 使用DHT11传感器 The DHT11 sensor was used
DHT dht(DHTPIN, DHTTYPE);  // 创建 DHT 对象，用于连接 DHT 传感器，指定传感器引脚和传感器型号 Create DHT objects for connecting DHT sensors, specifying sensor pins and sensor models

void setup() {
  Serial.begin(9600);
  Wire.begin();  //初始化 I2C 总线 SDA引脚设置为A4，SCL引脚设置为A5 The initial I2C bus SDA pin is set to A4 and the SCL pin is set to A5

  // 初始化 OLED 屏幕 Initializing the screen
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 initialization failed"));
    for (;;)
      ;
  }
  display.clearDisplay();  // 清空屏幕缓冲区 Clear the screen buffer
  dht.begin();             // 初始化 DHT11 传感器 Initialize the DHT11 sensor
}

void loop() {
  // 读取温湿度数据 Read the temperature and humidity data
  int humidity = dht.readHumidity();
  int temperature = dht.readTemperature();
  display.clearDisplay();// 清空屏幕缓冲区 Clear the screen buffer
  // 显示温湿度数据 Display temperature and humidity data
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(16, 20);
  display.print("Temperature: ");
  display.println(temperature);
  display.setCursor(16, 40);
  display.print("Humidity: ");
  display.print(humidity);
  display.println("%");
  display.display();// 更新显示
  delay(2000);  // 延迟2秒再进行下一次读取
}
