实验结果
温湿度显示在串口:
温湿度显示在OLED屏幕:
实验代码
#include "U8glib.h"
#include "DHT.h"U8GLIB_SSD1306_128X32 u8g(U8G_I2C_OPT_NONE);
#define DHTTYPE DHT22 // DHT 22 (AM2302)
#define DHTPIN 2 // what pin we're connected to
DHT dht(DHTPIN, DHTTYPE);void setup() {// put your setup code here, to run once:u8g.setFont(u8g_font_8x13B);u8g.setFontRefHeightText();u8g.setFontPosTop();Serial.begin(9600); Serial.println("DHTxx test!");dht.begin();
}void loop() {// put your main code here, to run repeatedly:float h = dht.readHumidity();float t = dht.readTemperature();delay(2000);// check if returns are valid, if they are NaN (not a number) then something went wrong!if (isnan(t) || isnan(h)) {Serial.println("Failed to read from DHT");} else {Serial.print("Humidity: "); Serial.print(h);Serial.print(" %\t");Serial.print("Temperature: "); Serial.print(t);Serial.println(" *C");u8g.firstPage();do{u8g.drawStr(0, 0, "Hum");u8g.setPrintPos(40, 0);u8g.print(h);u8g.print("%");u8g.drawStr(0, 20, "Temp");u8g.setPrintPos(40, 20);u8g.print(t);u8g.print("c");}while(u8g.nextPage());}
}
实验过程
先导入U8glib和DHT两个库,然后利用库里面的函数做测试,了解各个函数都是怎么用的,比如
U8glib里面有个循环模块,用于显示
u8g.firstpage();//图片循环模块do{draw();//自己写的函数}while (u8g.nextpage()) {delay(100);}
U8gilb里面 u8g.setPrintPos(40, 0);固定了下个输出在屏幕上的位置,第一个参数决定行,第二个参数决定列。
至于硬件的线如何连接,dth22的DAT引脚接Arduino的2引脚
OLED的SCL接Arduino的A5
OLED的SDA接Arduino的A4
其余的OLED和DTH22的GND,5V接Arduino的GND和5V。