標(biāo)題:
基于stm32單片機(jī)的DHT11溫濕度程序
[打印本頁(yè)]
作者:
優(yōu)秀的張小寒
時(shí)間:
2023-5-17 00:36
標(biāo)題:
基于stm32單片機(jī)的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);
}
}
復(fù)制代碼
#include "dht11.h"
#include "delay.h"
//復(fù)位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); //主機(jī)拉高20~40us
}
//等待DHT11的回應(yīng)
//返回1:未檢測(cè)到DHT11的存在
//返回0:存在
u8 DHT11_Check(void)
{
u8 retry=0;
DHT11_IO_IN();//SET INPUT
while (DHT11_DQ_IN&&retry<100)//DHT11會(huì)拉低40~80us
{
retry++;
delay_us(1);
};
if(retry>=100)return 1;
else retry=0;
while (!DHT11_DQ_IN&&retry<100)//DHT11拉低后會(huì)再次拉高40~80us
{
retry++;
delay_us(1);
};
if(retry>=100)return 1;
return 0;
}
//從DHT11讀取一個(gè)位
//返回值:1/0
u8 DHT11_Read_Bit(void)
{
u8 retry=0;
while(DHT11_DQ_IN&&retry<100)//等待變?yōu)榈碗娖?br />
{
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讀取一個(gè)字節(jié)
//返回值:讀到的數(shù)據(jù)
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讀取一次數(shù)據(jù)
//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位數(shù)據(jù)
{
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 同時(shí)檢測(cè)DHT11的存在
//返回1:不存在
//返回0:存在
u8 DHT11_Init(void)
{
RCC->APB2ENR|=1<<8; //使能PORTG口時(shí)鐘
GPIOG->CRH&=0XFFFF0FFF;//PORTG.11 推挽輸出
GPIOG->CRH|=0X00003000;
GPIOG->ODR|=1<<11; //輸出1
DHT11_Rst();
return DHT11_Check();
}
復(fù)制代碼
Keil代碼下載::
溫濕度oled -串口通信程序.7z
(188.92 KB, 下載次數(shù): 38)
2023-5-18 19:49 上傳
點(diǎn)擊文件名下載附件
下載積分: 黑幣 -5
歡迎光臨 (http://www.torrancerestoration.com/bbs/)
Powered by Discuz! X3.1