前言
本文是基于嵌入式开发板CT117E,stm32f103RBT6。
一、原理图
二、由原理图得到的信息
- 只有一个口 HDQ。
- 与PA7连接。
三、DHT11初始化
dht11.c
#include "stm32f10x.h"
#define delay_us(X) delayd(X*72/5)
void delayd(unsigned int n)
{
while (n--);
}
void dht11_init (void )
{
GPIO_InitTypeDef GPIO_InitStructure;
/* Enable clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA , ENABLE);
/* Configure Ports */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_SetBits(GPIOA, GPIO_Pin_7);
}
void mode_input(void )
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
void mode_output(void )
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
unsigned int dht11_read(void)
{
int i;
long long val;
int timeout;
GPIO_ResetBits(GPIOA, GPIO_Pin_7);
delay_us(18000); //pulldown for 18ms
GPIO_SetBits(GPIOA, GPIO_Pin_7);
delay_us( 20 ); //pullup for 30us
mode_input();
//等待DHT11拉高,80us
timeout = 5000;
while( (! GPIO_ReadInputDataBit (GPIOA, GPIO_Pin_7)) && (timeout > 0) ) timeout--; //wait HIGH
//等待DHT11拉低,80us
timeout = 5000;
while( GPIO_ReadInputDataBit (GPIOA, GPIO_Pin_7) && (timeout > 0) ) timeout-- ; //wait LOW
#define CHECK_TIME 28
for(i=0;i<40;i++)
{
timeout = 5000;
while( (! GPIO_ReadInputDataBit (GPIOA, GPIO_Pin_7)) && (timeout > 0) ) timeout--; //wait HIGH
delay_us(CHECK_TIME);
if ( GPIO_ReadInputDataBit (GPIOA, GPIO_Pin_7) )
{
val=(val<<1)+1;
} else {
val<<=1;
}
timeout = 5000;
while( GPIO_ReadInputDataBit (GPIOA, GPIO_Pin_7) && (timeout > 0) ) timeout-- ; //wait LOW
}
mode_output();
GPIO_SetBits(GPIOA, GPIO_Pin_7);
if (((val>>32)+(val>>24)+(val>>16)+(val>>8) -val ) & 0xff ) return 0;
else return val>>8;
}
dht11.h
#ifndef __DHT11_H
#define __DHT11_H
void dht11_init (void );
void delay(unsigned int n);
unsigned int dht11_read(void);
void DisplayDht11(void);
#endif
四、DHT11在主函数的应用方法
while(1)
{
v=dht11_read(); //读取32位值,前16位是湿度,后16位是温度,这里只取整数部分所以都是取各个16位的高8位
m= v>>24; //用湿度变量存起来,再进行字符串显示的拷贝
t=(v>>8)&0xff; //用温度变量存起来,再进行字符串显示的拷贝
sprintf((char *)buff,"Moisture: %d%% ",m); //拷贝的这个函数里面尽量不要放运算,容易出错
LCD_DisplayStringLine(Line4,buff);
sprintf((char *)buff,"Temperature: %d ",t);
LCD_DisplayStringLine(Line5,buff);
//seg_show(((v>>8)&0xff)/10, ((v>>8)&0xff)%10, 12);
Delay_Ms(2000); //最好延时2S以上为的就是保证你每次每次显示的的数据都是真正实时采集的
}