标题:
基于stm32单片机的DHT11温湿度程序
[打印本页]
作者:
优秀的张小寒
时间:
2023-5-17 00:36
标题:
基于stm32单片机的DHT11温湿度程序
主控stm32f103zet6传感器DHT11
oled是0.96寸4引脚iic
#include "delay.h"
#include "sys.h"
#include "oled.h"
#include "dht11.h"
#include "usart.h"
int main(void)
{
u8 temperature,humidity;
delay_init();
uart_init(115200); //串口初始化
printf("\r\n wecome to DHT11");
OLED_Init();
DHT11_Init();
OLED_Clear();
OLED_ShowString(0, 0, "temperature:",16);
OLED_ShowString(0, 2, "humidity:",16);
while (1)
{
if (DHT11_Read_Data(&temperature,&humidity) == 0)
{
char temp[20], humi[20];
sprintf(temp, "%d%dC", temperature / 10, temperature % 10);
sprintf(humi, "%d%d%%", humidity / 10, humidity % 10);
OLED_ShowString(95, 0, temp,16);
OLED_ShowString(95, 2, humi,16);
printf("\r\n temperature:%d℃,humidity:%d",temperature,humidity);
}
else
{ printf("\r\n EEROR! THE DHT11 HAS NO RESPOND...");
delay_ms(100);
}
delay_ms(1000);
}
}
复制代码
#include "dht11.h"
#include "delay.h"
//复位DHT11
void DHT11_Rst(void)
{
DHT11_IO_OUT(); //SET OUTPUT
DHT11_DQ_OUT=0; //拉低DQ
delay_ms(20); //拉低至少18ms
DHT11_DQ_OUT=1; //DQ=1
delay_us(30); //主机拉高20~40us
}
//等待DHT11的回应
//返回1:未检测到DHT11的存在
//返回0:存在
u8 DHT11_Check(void)
{
u8 retry=0;
DHT11_IO_IN();//SET INPUT
while (DHT11_DQ_IN&&retry<100)//DHT11会拉低40~80us
{
retry++;
delay_us(1);
};
if(retry>=100)return 1;
else retry=0;
while (!DHT11_DQ_IN&&retry<100)//DHT11拉低后会再次拉高40~80us
{
retry++;
delay_us(1);
};
if(retry>=100)return 1;
return 0;
}
//从DHT11读取一个位
//返回值:1/0
u8 DHT11_Read_Bit(void)
{
u8 retry=0;
while(DHT11_DQ_IN&&retry<100)//等待变为低电平
{
retry++;
delay_us(1);
}
retry=0;
while(!DHT11_DQ_IN&&retry<100)//等待变高电平
{
retry++;
delay_us(1);
}
delay_us(40);//等待40us
if(DHT11_DQ_IN)return 1;
else return 0;
}
//从DHT11读取一个字节
//返回值:读到的数据
u8 DHT11_Read_Byte(void)
{
u8 i,dat;
dat=0;
for (i=0;i<8;i++)
{
dat<<=1;
dat|=DHT11_Read_Bit();
}
return dat;
}
//从DHT11读取一次数据
//temp:温度值(范围:0~50°)
//humi:湿度值(范围:20%~90%)
//返回值:0,正常;1,读取失败
u8 DHT11_Read_Data(u8 *temp,u8 *humi)
{
u8 buf[5];
u8 i;
DHT11_Rst();
if(DHT11_Check()==0)
{
for(i=0;i<5;i++)//读取40位数据
{
buf[i]=DHT11_Read_Byte();
}
if((buf[0]+buf[1]+buf[2]+buf[3])==buf[4])
{
*humi=buf[0];
*temp=buf[2];
}
}else return 1;
return 0;
}
//初始化DHT11的IO口 DQ 同时检测DHT11的存在
//返回1:不存在
//返回0:存在
u8 DHT11_Init(void)
{
RCC->APB2ENR|=1<<8; //使能PORTG口时钟
GPIOG->CRH&=0XFFFF0FFF;//PORTG.11 推挽输出
GPIOG->CRH|=0X00003000;
GPIOG->ODR|=1<<11; //输出1
DHT11_Rst();
return DHT11_Check();
}
复制代码
Keil代码下载::
温湿度oled -串口通信程序.7z
(188.92 KB, 下载次数: 38)
2023-5-18 19:49 上传
点击文件名下载附件
下载积分: 黑币 -5
欢迎光临 (http://www.51hei.com/bbs/)
Powered by Discuz! X3.1