写一个dht11显示在lcd屏上,并用HCsr04测距的程序,C51,并距离<10的时候报警
时间: 2023-06-27 15:04:29 浏览: 106
以下是基于C51单片机的DHT11和HC-SR04测距的程序,将温湿度数据显示在16x2 LCD上,并在距离小于10cm时触发蜂鸣器报警。
```c
#include <reg51.h>
#include <intrins.h>
#define LCD_RS P1_0
#define LCD_RW P1_1
#define LCD_EN P1_2
#define LCD_DATA P2
sbit TRIG = P3^5;
sbit ECHO = P3^4;
sbit BUZZER = P3^7;
unsigned char code lcd_init[] = {0x38,0x08,0x01,0x06,0x0c};
unsigned char humi_data = 0, temp_data = 0;
unsigned int distance = 0;
void delay(unsigned int t) {
while(t--);
}
void lcd_write_cmd(unsigned char cmd) {
LCD_RS = 0;
LCD_RW = 0;
LCD_DATA = cmd;
LCD_EN = 1;
_nop_();
_nop_();
LCD_EN = 0;
delay(5);
}
void lcd_write_data(unsigned char dat) {
LCD_RS = 1;
LCD_RW = 0;
LCD_DATA = dat;
LCD_EN = 1;
_nop_();
_nop_();
LCD_EN = 0;
delay(5);
}
void lcd_init_seq() {
unsigned char i;
for (i = 0; i < 5; i++) {
lcd_write_cmd(lcd_init[i]);
delay(5);
}
}
void lcd_display(unsigned char row, unsigned char col, unsigned char *str) {
unsigned char addr;
if (row == 0) addr = 0x80 + col;
else addr = 0xc0 + col;
lcd_write_cmd(addr);
while (*str) {
lcd_write_data(*str++);
}
}
void dht11_start() {
P3_3 = 0;
delay(20);
P3_3 = 1;
delay(30);
P3_3 = 0;
}
unsigned char dht11_read_byte() {
unsigned char i, dat = 0;
for (i = 0; i < 8; i++) {
while(!P3_3);
delay(30);
if (P3_3) dat |= (1 << (7 - i));
while(P3_3);
}
return dat;
}
void dht11_read() {
unsigned char rh_integral, rh_decimal, temp_integral, temp_decimal, check_sum;
dht11_start();
if (!P3_3) {
while(!P3_3);
while(P3_3);
rh_integral = dht11_read_byte();
rh_decimal = dht11_read_byte();
temp_integral = dht11_read_byte();
temp_decimal = dht11_read_byte();
check_sum = dht11_read_byte();
if (check_sum == rh_integral + rh_decimal + temp_integral + temp_decimal) {
humi_data = rh_integral;
temp_data = temp_integral;
}
}
}
void hcsr04_measure() {
unsigned long t;
TRIG = 0;
delay(10);
TRIG = 1;
delay(10);
TRIG = 0;
while(!ECHO);
t = 0;
while(ECHO) {
t++;
delay(1);
}
distance = t / 58;
}
void main() {
unsigned char str[16];
lcd_init_seq();
while(1) {
dht11_read();
hcsr04_measure();
if (distance < 10) {
BUZZER = 1;
} else {
BUZZER = 0;
}
sprintf(str, "H:%d.%d%% T:%d.%dC", humi_data, temp_data, temp_data, humi_data);
lcd_display(0, 0, str);
sprintf(str, "Distance:%dcm", distance);
lcd_display(1, 0, str);
delay(500);
}
}
```
注意,该程序中使用的是P3.3作为DHT11的数据引脚,P3.5作为HC-SR04的TRIG引脚,P3.4作为HC-SR04的ECHO引脚,P3.7作为蜂鸣器引脚。
另外,需要在程序中添加LCD相关的头文件和函数,这里就不再贴出。
阅读全文