Arduino測量溫濕度(DHT22)並顯示在串口和OLED顯示屏上


實驗結果

溫濕度顯示在串口:
在這里插入圖片描述
溫濕度顯示在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。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM