目录
介绍
DHT11是一种单线数字湿度和温度传感器,可连续提供湿度和温度值。
它可以测量相对湿度的百分比(20至90%RH)和温度(摄氏度),范围为0至50°C。
它有4个引脚,其中2个引脚用于供电,1个未使用,最后一个引脚用于数据。
数据是唯一用于通信的引脚。不同TON和TOFF的脉冲被解码为逻辑1或逻辑0或起始脉冲或帧的结束。
DHT11传感器
电路原理图
DHT11传感器与8051连接方法
- 上面的电路图显示了8051与DHT11传感器的连接方法。
- 其中,DHT11传感器连接到微控制器的P2.1(引脚号22)
编程步骤
- 首先,初始化LCD16x2_4bit.h库。
- 定义引脚号。连接DHT11传感器,在我们的程序中我们定义P2.1(第22号引脚)
- 通过将数据引脚从低电平变为高电平,将启动脉冲发送到DHT11传感器。
- 从DHT11传感器接收响应脉冲。
- 收到响应后,从DHT11传感器串行接收40位数据。
- 在LCD16x2上显示此接收数据以及错误指示
程序
/*
* DHT11 Interfacing with 8051
* https://www.qutaojiao.com
*/
#include<reg51.h>
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
#include "LCD16x2_4bit.h"
sbit DHT11=P2^1; /* Connect DHT11 output Pin to P2.1 Pin */
int I_RH,D_RH,I_Temp,D_Temp,CheckSum;
void timer_delay20ms() /* Timer0 delay function */
{
TMOD = 0x01;
TH0 = 0xB8; /* Load higher 8-bit in TH0 */
TL0 = 0x0C; /* Load lower 8-bit in TL0 */
TR0 = 1; /* Start timer0 */
while(TF0 == 0); /* Wait until timer0 flag set */
TR0 = 0; /* Stop timer0 */
TF0 = 0; /* Clear timer0 flag */
}
void timer_delay30us() /* Timer0 delay function */
{
TMOD = 0x01; /* Timer0 mode1 (16-bit timer mode) */
TH0 = 0xFF; /* Load higher 8-bit in TH0 */
TL0 = 0xF1; /* Load lower 8-bit in TL0 */
TR0 = 1; /* Start timer0 */
while(TF0 == 0); /* Wait until timer0 flag set */
TR0 = 0; /* Stop timer0 */
TF0 = 0; /* Clear timer0 flag */
}
void Request() /* Microcontroller send request */
{
DHT11 = 0; /* set to low pin */
timer_delay20ms(); /* wait for 20ms */
DHT11 = 1; /* set to high pin */
}
void Response() /* Receive response from DHT11 */
{
while(DHT11==1);
while(DHT11==0);
while(DHT11==1);
}
int Receive_data() /* Receive data */
{
int q,c=0;
for (q=0; q<8; q++)
{
while(DHT11==0);/* check received bit 0 or 1 */
timer_delay30us();
if(DHT11 == 1) /* If high pulse is greater than 30ms */
c = (c<<1)|(0x01);/* Then its logic HIGH */
else /* otherwise its logic LOW */
c = (c<<1);
while(DHT11==1);
}
return c;
}
void main()
{
unsigned char dat[20];
LCD_Init(); /* initialize LCD */
while(1)
{
Request(); /* send start pulse */
Response(); /* receive response */
I_RH=Receive_data(); /* store first eight bit in I_RH */
D_RH=Receive_data(); /* store next eight bit in D_RH */
I_Temp=Receive_data(); /* store next eight bit in I_Temp */
D_Temp=Receive_data(); /* store next eight bit in D_Temp */
CheckSum=Receive_data();/* store next eight bit in CheckSum */
if ((I_RH + D_RH + I_Temp + D_Temp) != CheckSum)
{
LCD_String_xy(0,0,"Error");
}
else
{
sprintf(dat,"Hum = %d.%d",I_RH,D_RH);
LCD_String_xy(0,0,dat);
sprintf(dat,"Tem = %d.%d",I_Temp,D_Temp);
LCD_String_xy(1,0,dat);
LCD_Char(0xDF);
LCD_String("C");
memset(dat,0,20);
sprintf(dat,"%d ",CheckSum);
LCD_String_xy(1,13,dat);
}
delay(100);
}
}
本教程完整工程项目下载: