写一个dht11显示在lcd屏上,并用HCsr04测距的程序
时间: 2023-06-27 20:04:41 浏览: 122
以下是一个使用DHT11和HC-SR04的Arduino程序,它将读取温度,湿度和距离,并将它们显示在LCD屏幕上:
```
#include <dht.h>
#include <LiquidCrystal.h>
#define DHT11_PIN 7
dht DHT;
#define TRIG_PIN 9
#define ECHO_PIN 10
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
lcd.begin(16, 2);
lcd.print("Temp: ");
lcd.setCursor(0, 1);
lcd.print("Humidity: ");
}
void loop() {
// Read temperature and humidity from DHT11
int chk = DHT.read11(DHT11_PIN);
float temp = DHT.temperature;
float humidity = DHT.humidity;
// Read distance from HC-SR04
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
float duration = pulseIn(ECHO_PIN, HIGH);
float distance = duration * 0.034 / 2;
// Display readings on LCD
lcd.setCursor(6, 0);
lcd.print(temp);
lcd.print((char)223);
lcd.print("C");
lcd.setCursor(10, 1);
lcd.print(humidity);
lcd.print("%");
lcd.setCursor(0, 1);
lcd.print("Humidity: ");
lcd.setCursor(0, 0);
lcd.print("Temp: ");
delay(1000);
}
```
该程序首先引入两个库:dht和LiquidCrystal。然后定义了DHT11引脚和TRIG_PIN/ECHO_PIN。在setup()函数中,将TRIG_PIN设置为输出,将ECHO_PIN设置为输入,初始化LCD,并在屏幕上打印温度和湿度。
在loop()中,程序将从DHT11读取温度和湿度,并从HC-SR04读取距离。然后,程序将读数显示在LCD上,并延迟1秒钟,以便读数更新。
阅读全文