硬件:开发板(本人用的STC89C52RC),温湿度模块(DHT11),杜邦线
如果感觉自己没问题但就是实现不了现象可能是DHT11模块损坏,可以看我检验DHT11模块的代码
#include <reg52.h>
#include <intrins.h>
sfr AUXR = 0x8e;
sbit D5 = P3^7;
sbit dht = P3^5;
char datas[5] ={'\0'};
void UartInit(){ //9600bps@11.0592MHz
//PCON &= 0x7F; //波特率不倍速
SCON = 0x52; //串口工作方式1,REN不使能,TI可用
AUXR = 0x01; //定时器1时钟为Fosc/12,即12T
TMOD &= 0x0F; //清除定时器1模式位
TMOD |= 0x20; //设定定时器1为8位自动重装方式
TL1 = 0xFD; //设定定时初值
TH1 = 0xFD; //设定定时器重装值
TR1 = 1; //启动定时器1
}//配置通信方式
void sendByte(char massage){
SBUF = massage;
while(!TI);
TI = 0;
} //发送一个字符
void sendString(char* str){
while(*str != '\0'){
sendByte(*str);
str++;
}
}
void Delay40us(){
unsigned char i;
_nop_();
i = 15;
while (--i);
}
void Delay18ms(){
unsigned char i, j;
i = 33;
j = 66;
do{
while (--j);
}while (--i);
}//延时18 ms
void Delay1000ms(){
unsigned char i, j, k;
_nop_();
i = 8;
j = 1;
k = 243;
do{
do{
while (--k);
}while (--j);
}while (--i);
}
void DTH11_START(){
dht = 1;
dht = 0;
Delay18ms(); //延时18 ms以启动模块
dht = 1; //软件拉高电平
while(dht);
while(!dht);
while(dht);
}//根据模块时序图检测模块是否开始读取数据
void Read_Data_From_DTH11(){
int i;
int j;
char temp;
char flag;
DTH11_START();
for(i = 0;i < 5;i++){
for(j = 0;j < 8;j++){
while(!dht);
Delay40us();
if(dht){
flag = 1;
while(dht);
}else{
flag = 0;
}
temp = temp << 1;
temp = temp | flag;
}
datas[i] = temp;
}
}
void main(){
UartInit();
Delay1000ms();
Delay1000ms(); //上电后延迟2 s让模块恢复稳定状态
while(1){
Delay1000ms();
Delay1000ms(); //每次读数据时延迟1 s防止数据出错
Read_Data_From_DTH11();
sendString("H:");
sendByte(datas[0] / 10 + 0x30);
sendByte(datas[0] % 10 + 0x30);
sendString(".");
sendByte(datas[1] / 10 + 0x30);
sendByte(datas[1] % 10 + 0x30);
sendString("\r\n");
sendString("T:");
sendByte(datas[2] / 10 + 0x30);
sendByte(datas[2] % 10 + 0x30);
sendString(".");
sendByte(datas[3] / 10 + 0x30);
sendByte(datas[3] % 10 + 0x30);
sendString("\r\n");
D5 = 0;
}
}