嵌入式-DHT11驱动代码

DHT11是一款数字型的温湿度传感器,可以采集到外界环境的温湿度值,将采集到的数据在传感器内部转换成数字量发送给单片机。

/********************************************************************************
*
*
* DHT11驱动接口
* author:jindouliu2024@163.com 
* date:2025.4.10
* 
*
* Copyright (c)  2024-2025   jindouliu2024@163.com   All right Reserved
********************************************************************************/

DHT11.C

#include "stm32f10x.h"
#include "Delay.h"
uint8_t *humh,*huml,*temph,*templ;
void dht11_input()
{
	GPIO_InitTypeDef GPIO_InitStructure;					
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;		
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;				
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;		
	GPIO_Init(GPIOB, &GPIO_InitStructure);
}
void dht11_output()
{
	GPIO_InitTypeDef GPIO_InitStructure;					
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;		
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;				
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;		
	GPIO_Init(GPIOB, &GPIO_InitStructure);
}
void dht11_Init()
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);										//使用各个外设前必须开启时钟,否则对外设的操作无效

	GPIO_InitTypeDef GPIO_InitStructure;					
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;		
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;				
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;		
	GPIO_Init(GPIOB, &GPIO_InitStructure);
	
	GPIO_SetBits(GPIOB,GPIO_Pin_2);
	Delay_s(1);

}

void dht11_getdata(uint8_t *humh,uint8_t *huml,uint8_t *temph,uint8_t *templ)
{
	uint8_t byte,data[5]={0x00,0x00,0x00,0x00,0x00};
	/*主机发送起始信号*/
	dht11_output();
	GPIO_ResetBits(GPIOB,GPIO_Pin_2);
	Delay_ms(20);
	GPIO_SetBits(GPIOB,GPIO_Pin_2);
	Delay_us(20);
	dht11_input();
	while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_2)==0);//从机应答
	while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_2)==1);//从机发送准备接受数据信号
	for(uint8_t i=0;i<5;i++)
	{
		for(uint8_t j=0;j<8;j++)
		{
			while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_2)==0);
			Delay_us(45);
			byte=GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_2);
			if(byte==1)
			{
				data[i]|=(byte<<(8-j-1));
				while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_2)==1);
			}
			else
			{
				while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_2)==0);
			}
		}
		
	}
	while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_2)==0);//数据传输结束
	dht11_output();
	GPIO_SetBits(GPIOB,GPIO_Pin_2);
	if(data[0]+data[1]+data[2]+data[3]==data[4])
	{
		*humh=data[0];
		*huml=data[1];
		*temph=data[2];
		*templ=data[3];	
	}
}

DHT11.h

#ifndef __DHT11_H
#define __DHT11_H
void dht11_Init();
void dht11_getdata(uint8_t *humh,uint8_t *huml,uint8_t *temph,uint8_t *templ);
#endif
posted @ 2025-04-10 20:26  LRadian  阅读(167)  评论(0)    收藏  举报