Skip to content

Instantly share code, notes, and snippets.

@joy224961632
Created November 22, 2019 02:37
Show Gist options
  • Save joy224961632/11aa1aa1868b9e61f432c0e22bb2863b to your computer and use it in GitHub Desktop.
Save joy224961632/11aa1aa1868b9e61f432c0e22bb2863b to your computer and use it in GitHub Desktop.
#include "DHT.h" //預載感測器所需之程式庫
#define DHTPIN D6 //預先定義 感測器信號名稱 接腳位置在 D6
#define redLED D1 //預先定義 LED 接腳位置
#define greenLED D2
#define blueLED D3
#define relayPin D4 //預先定義 繼電器 接腳位置
// 依感測器使用型號,移除該行之註解符號
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
//使用程式庫定義 感測裝置名稱(信號腳位,感測器型號)
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
Serial.println("DHT11 test!"); //於序列步監控視窗顯示提示訊息
dht.begin(); //感測器裝置啟動致能
pinMode(redLED,OUTPUT); //LED腳位設為輸出
pinMode(greenLED,OUTPUT);
pinMode(blueLED,OUTPUT);
pinMode(relayPin,OUTPUT); //繼電器腳位設為輸出
}
void loop() {
// Wait a few seconds between measurements.
delay(2000); //延時2秒
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity(); //浮點數變數 h 存放 讀取濕度數值
// Read temperature as Celsius (the default) 預設讀取的溫度是"攝氏"
float t = dht.readTemperature(); //浮點數變數 t 存放 讀取攝氏溫度數值
// Read temperature as Fahrenheit (isFahrenheit = true) 讀取華氏溫度時,參數=true
float f = dht.readTemperature(true); //浮點數變數 f 存放 讀取華氏溫度數值
// 以下判斷是否讀取失敗=(無濕度值或無攝氏值或無華氏值)
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!"); //顯示讀取失敗訊息
return; //脫離本函式且返回主程式
}
Serial.print("Humidity: ");
Serial.print(h); //顯示濕度值
Serial.print(" %\t"); //顯示單位且跳一個Tab格
Serial.print("Temperature: ");
Serial.print(t); //顯示攝氏溫度值
Serial.print(" °C = "); //顯示單位
Serial.print(f); //顯示華氏溫度值
Serial.println(" °F"); //顯示單位
if (t<28) //若 濕度大於80%,則
{
digitalWrite(redLED,HIGH); //點亮共陽型紅燈
digitalWrite(greenLED,LOW); //滅掉綠燈
digitalWrite(blueLED,HIGH);
}
else if(t> 28 & t < 30) //若 濕度未大於80%,則
{
digitalWrite(redLED,LOW); //滅掉紅燈
digitalWrite(greenLED,LOW); //點亮綠燈
digitalWrite(blueLED,HIGH);
}
else{
digitalWrite(redLED,LOW); //滅掉紅燈
digitalWrite(greenLED,HIGH); //點亮綠燈
digitalWrite(blueLED,HIGH);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment