#include<dht11.h>
#include<LiquidCrystal.h>
LiquidCrystal LCD(11,12,5,4,3,2); //宣告一個名為LCD的LiquidCrystal
dht11 DHT; //宣告一個名為DHT的dht11
int trig = 9,echo = 10,buzzer = 6;
float cm;
void setup() {
LCD.begin(16,2); //初始化LCD
pinMode(buzzer,OUTPUT); //初始化蜂鳴器
pinMode(trig,OUTPUT); //初始化超音波發射器為OUTPUT
pinMode(echo,INPUT); //初始化超音波接收器為INPUT
}
void loop() {
if(DHT.read(8) == 0) //如果讀取成功輸出溫度和濕度
{
showdht(); //顯示溫度濕度
bibi(); //蜂鳴器叫兩聲
delay(2000);
LCD.clear();
showdis(); //顯示距離
bibi();
delay(2000);
}
else{ //讀取失敗則輸出Error
LCD.setCursor(0,0);
LCD.print("Error");
}
LCD.clear(); //清除畫面
}
void bibi() //嗶嗶兩聲
{
for(int i = 1;i <= 100;i++) //每隔4ms鳴叫一次重複100次
{
digitalWrite(buzzer,HIGH);
delay(1);
digitalWrite(buzzer,LOW);
delay(1);
}
delay(100);
for(int i = 1;i <= 100;i++) //每隔4ms鳴叫一次重複100次
{
digitalWrite(buzzer,HIGH);
delay(1);
digitalWrite(buzzer,LOW);
delay(1);
}
}
void showdht() //用來輸出溫度濕度
{
LCD.setCursor(0,0);
LCD.print("Temperature:");
LCD.print((float)DHT.temperature,2);
LCD.print("c");
LCD.setCursor(0,1);
LCD.print("Humidity:");
LCD.print((float)DHT.humidity,2);
LCD.print("%");
}
void showdis() //用來計算和輸出距離
{
//trig發出脈衝
digitalWrite(trig,LOW);
delayMicroseconds(2);
digitalWrite(trig,HIGH);
delayMicroseconds(10);
digitalWrite(trig,LOW);
//接收時間
long etime = pulseIn(echo,HIGH);//等到pin到HIGH之後開始計時直到LOW 回傳Microseconds;
//計算距離
cm = etime*(331+0.6*(float)DHT.temperature)/2/10000;
LCD.setCursor(0,0);
LCD.print("Distance:");
LCD.setCursor(0,1);
LCD.print(cm);
LCD.print("cm");
}

Hubert's Coding Notes
Useful notes for CS people