51单片机 使用DHT11温湿度模块

#include <REGX52.H>
#include <INTRINS.H>
#include "DHT11.h"
#include "LCD1602.h"

sbit DHT11 = P1^0;

/**
  *  @brief  DHT11初始化函数:上电置高电平1s      
 */	
void DHT11_Init(void)
{
	DHT11 = 1;
	Delay_ms(1000);
}
/**
  *  @brief  DHT11开始函数:拉低总线        
 */	
void DHT11_Start(void)
{
	//拉低23毫秒 
	DHT11 = 0;
	Delay_ms(23);
	DHT11 = 1;
	//拉低后等待DHt11拉低数据并释放总线
	Delay40us();
	while(DHT11 == 0);
	while(DHT11 == 1);
}
/**
  *  @brief  DHT11接收一个位        
 */	
unsigned char DHT11_ReceiveBit(void)
{
	while(DHT11 == 1);
	while(DHT11 == 0);
	Delay40us();
	if(DHT11 == 1)
	{
		return 1;
	}
	else
	{
		return 0;
	}
	/*如果接收到的数据为1,那么return后DHT11还未将总线拉低
		while(DHT11 == 1)的作用为了等待总线拉低*/
	/*如果接收到的数据为0,那么return后DHT11已经将总线拉低(下一段时序的低电平)
		while(DHT11 == 0)的作用为了等待总线被拉高*/	
}
/**
  *  @brief  DHT11接收一个字节        
 */	
unsigned char DHT11_ReceiveByte(void)
{
	unsigned char Byte = 0;
	unsigned char i;
	for(i=0;i<8;i++)
	{
		if(DHT11_ReceiveBit() == 1)
		{
			Byte |= (0x80>>i);
		}	
	}
	return Byte;
}
/**
  *  @brief  DHT11接收40位数据(5个字节)       
 */	
void DHT11_Receive40Data(unsigned char *Wet,unsigned char *Wets,unsigned char *Temp,unsigned char *Temps,unsigned char *Check)//
{
	unsigned char i;
	unsigned char Byte[5] = {0,0,0,0,0};
	DHT11_Start();
	for(i=0;i<40;i++)
	{
		if(DHT11_ReceiveBit() == 1)
		{
			Byte[i/8] |= (0x80>>(i%8));
		}	
	}
	*Wet 	=   Byte[0];
	*Wets 	=   Byte[1];
	*Temp 	=   Byte[2];
	*Temps 	=   Byte[3];
	*Check	=   Byte[4];	
}
/**
  *  @brief  DHT11发送湿度、温度并校验整理数据       
 */	
void DHT11_Receive_Wet_Temp(unsigned char *Wet,float *Temp)
{
	unsigned char Byte[5];
	while(1)
	{
		DHT11_Receive40Data(Byte,Byte+1,Byte+2,Byte+3,Byte+4);
		if(Byte[0]+Byte[1]+Byte[2]+Byte[3] == Byte[4])  break;//如果校验成功退出死循环,否则持续接收数据
	}
	*Wet 	= 	Byte[0];						//湿度
	*Temp  	= 	Byte[2]+(Byte[3]/10.0);			//温度
}

DHT11的上电后需要等待一秒钟,单片机拉低总线后,DHT相应一组高低电平后就会开始连续的40个数据发送,接收1时,高电平时间会久一些,该代码是根据开发手册写的,程序可以正常运行。

#include "DHT11.h"
#include "Delay.h"
#include "LCD1602.h"
unsigned char A1,B1,C1,D1,E1,Temp;
unsigned char wet;
float temps;
void main()
{
	DHT11_Init();
	LCD_Init(); 
	while(1)
	{
		
		DHT11_Receive_Wet_Temp(&wet,&temps);
		
		LCD_ShowNum(1,1,wet,2);
		LCD_ShowString(1,3,"%");
		
		LCD_ShowNum(2,1,temps,2);
		LCD_ShowString(2,3,".");
		LCD_ShowNum(2,4,((unsigned char)(temps*10)%10),1);
		LCD_ShowString(2,5,"^");
		LCD_ShowString(2,6,"C");
		
		Delay(2000);		
	}
}

Savage—如有错误,请大家提出指正,也欢迎大家一起交流 

  • 1
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值