#include <dht.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
/*-------------------DHT22-------------------------*/
#define dataDHT 8
dht DHT1;
/*-------------------SSD1306-------------------------*/
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C
Adafruit_SSD1306 screen(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
/*-------------------SSD1306-------------------------*/
if(!screen.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
// Clear the buffer.
screen.clearDisplay();
// Display Text
screen.setTextSize(1);
screen.setTextColor(WHITE);
screen.setCursor(0,0);
screen.println("Temperature:");
screen.setCursor(0,20);
screen.println("Humidity:");
screen.display();
}
void loop() {
// put your main code here, to run repeatedly:
int readData = DHT1.read22(dataDHT);
float t = DHT1.temperature;
float h = DHT1.humidity;
Serial.print("Temperature:");
Serial.print(t); Serial.println("°C");
Serial.print("Humidity:");
Serial.print(h); Serial.println("%");
screen.fillRect(80, 0, 48, 16, BLACK); // 清除上次温度显示的位置
screen.fillRect(80, 20, 48, 16, BLACK); // 清除上次湿度显示的位置
screen.setCursor(80, 0); // 温度数值位置
screen.print(t);
screen.print(" C");
screen.setCursor(80, 20); // 湿度数值位置
screen.print(h);
screen.print(" %");
screen.display(); // 更新显示
delay(2000); // 每2秒更新一次
}