基于STM8的DHT11溫濕度傳感器的驅(qū)動代碼設(shè)計
#include "typedef.h"
#include
#include "TemDHT11.h"
#ifndef _DHT11_TYPE
#define _DHT11_TYPE
//連接端口
#define DHT11_Dir P2DIR
#define DHT11_In P2IN
#define DHT11_Out P2OUT
#define DHT11_Bit BIT4
#endif
//8bit濕度+8bit濕度小數(shù)點
//8bit溫度+8bit溫度小數(shù)點
//數(shù)據(jù)位為0是高電平26~28us | 1高電平70us
u8 DHT11_Data[5] = {0}; //從DHT11中讀到的數(shù)據(jù)
void read_DHT11(u8 *Data)
{
u8 re,m,n,Time_out;
DHT11_Dir &= (~DHT11_Bit); //引腳為輸入
for(n = 0; n < 5; n++)
{
for(m = 0; m < 8; m++)
{
while( !(DHT11_In & DHT11_Bit) ); //每1bit以50us低電平時限開始,直到高電平到來
delay_us(30);
re = 0;
if((DHT11_In & DHT11_Bit)) //30us后還是高電平說明是1
{
re = 1;
}
Time_out = 2;
while((DHT11_In & DHT11_Bit) && (Time_out++ ));
if(Time_out == 1) //超時處理
{
break;
}
*Data <<= 1;
if(re)
{
*Data |= 0x01;
}
}
Data++;
}
}
//DHT11的握手協(xié)議模擬和數(shù)據(jù)的讀取
u8 DHT11_GetData(void)
{
u8 o,sum;
DHT11_Dir |= DHT11_Bit;
DHT11_Out &= ~DHT11_Bit; //拉低,發(fā)出開始信號
delay_ms(18); //拉低18ms
DHT11_Out |= DHT11_Bit; //拉高20us等待
delay_us(20);
DHT11_Dir &= (~DHT11_Bit);
if( !(DHT11_In & DHT11_Bit) ) //DHT11響應(yīng)
{
while( !(DHT11_In & DHT11_Bit) ); //80us低電平,等待DHT11的響應(yīng)信號
while( (DHT11_In & DHT11_Bit) ); //DHT11準備發(fā)送數(shù)據(jù)
read_DHT11(DHT11_Data); //主機接收數(shù)據(jù)
sum = 0;
for(o = 0; o < 4; o++) //數(shù)據(jù)校驗
{
sum += DHT11_Data[o];
}
if(sum != DHT11_Data[4])
{
return 0;
}
else
{
return 1;
}
}
return 0;
}
//對溫度濕度進行格式化(如果獲取溫度成功)
void DHT11_format(char *Des_str)
{
Des_str[0] = DHT11_Data[0]/10 + 0x30;
Des_str[1] = DHT11_Data[0] + 0x30;
Des_str[2] = '.';
Des_str[3] = DHT11_Data[1]/10 + 0x30;
Des_str[4] = DHT11_Data[1] + 0x30;
Des_str[5] = '%';
Des_str[6] = ' ';
Des_str[7] = DHT11_Data[2]/10 + 0x30;
Des_str[8] = DHT11_Data[2] + 0x30;
Des_str[9] = '.';
Des_str[10] = DHT11_Data[3]/10 + 0x30;
Des_str[11] = DHT11_Data[3] + 0x30;
Des_str[12] = 'C';
Des_str[13] = 0;
}