CC2530+DHT11測溫度

DHT11是一款有已校準數字信號輸出的溫溼度傳感器。 其精度溼度+-5%RH, 溫度+-2℃,量程溼度20-90%RH, 溫度0~50℃。


 

data線連接P0_0

  • DHT11.h
#include <ioCC2530.h>
#define uint unsigned int
#define uchar unsigned char
#define DATA_PIN P0_0

//溫溼度定義

uchar ucharFLAG,uchartemp;
uchar shidu_shi,shidu_ge,wendu_shi,wendu_ge=4;
uchar ucharT_data_H,ucharT_data_L,ucharRH_data_H,ucharRH_data_L,ucharcheckdata;
uchar ucharT_data_H_temp,ucharT_data_L_temp,ucharRH_data_H_temp,ucharRH_data_L_temp,ucharcheckdata_temp;
uchar ucharcomdata;

//延時函數
void Delay_us() //1 us 延時
{
asm("nop");//如果太多,很有可能校驗通不過
asm("nop");
asm("nop");
asm("nop");
}

void Delay1_10us() //10 us 延時
{
Delay_us();
Delay_us();
}

void Delay_ms(uint Time)//n ms 延時
{
unsigned char i;
while(Time--)
{
for(i=0;i<100;i++)
Delay1_10us();
}
}

//溫溼度傳感
void COM(void) // 溫溼寫入
{
uchar i;
for(i=0;i<8;i++)
{
ucharFLAG=2;
while((!DATA_PIN)&&ucharFLAG++);
Delay1_10us();
Delay1_10us();
Delay1_10us();
uchartemp=0;
if(DATA_PIN)uchartemp=1;
ucharFLAG=2;
while((DATA_PIN)&&ucharFLAG++);
if(ucharFLAG==1)break;
ucharcomdata<<=1;
ucharcomdata|=uchartemp;
}
}

void DHT11(void) //溫溼傳感啓動
{
DATA_PIN=0;
Delay_ms(30); //>18MS
DATA_PIN=1;
P0DIR &= ~0x01; //重新配置 IO 口方向 輸入
Delay1_10us();
Delay1_10us();
Delay1_10us();
Delay1_10us();
if(!DATA_PIN)
{
ucharFLAG=2;
while((!DATA_PIN)&&ucharFLAG++);
ucharFLAG=2;
while((DATA_PIN)&&ucharFLAG++);
COM();
ucharRH_data_H_temp=ucharcomdata;
COM();
ucharRH_data_L_temp=ucharcomdata;
COM();
ucharT_data_H_temp=ucharcomdata;
COM();
ucharT_data_L_temp=ucharcomdata;
COM();
ucharcheckdata_temp=ucharcomdata;
DATA_PIN=1;
uchartemp=(ucharT_data_H_temp+ucharT_data_L_temp+ucharRH_data_H_temp+ucharRH_data_L_temp);

if(uchartemp==ucharcheckdata_temp)
{
ucharRH_data_H=ucharRH_data_H_temp;
ucharRH_data_L=ucharRH_data_L_temp;
ucharT_data_H=ucharT_data_H_temp;
ucharT_data_L=ucharT_data_L_temp;
ucharcheckdata=ucharcheckdata_temp;
wendu_shi=ucharT_data_H/10;
wendu_ge=ucharT_data_H%10;
shidu_shi=ucharRH_data_H/10;
shidu_ge=ucharRH_data_H%10;
}
else //沒用成功讀取,重新運行函數
{
  DHT11();
}
}
P0DIR |= 0x01; //IO 口需要重新配置
}




 

調用函數getWS()即可得到當前的溫溼度。

  • DHT11.c
#include "DHT11.h"
#include <ioCC2530.h>
#include <string.h>

#define uint unsigned int
#define uchar unsigned char
char temp_humidity[4]; 
extern char* getWS(void);
void DelayMS(uint msec)
{
uint i,j;
for (i=0; i<msec; i++)
for (j=0; j<1070; j++);
}
char* getWS(void){ 
  memset(temp_humidity, 0, 4);
  DHT11();
  temp_humidity[2]=(char)wendu_shi+0x30;//轉化爲Char類型
  temp_humidity[3]=(char)wendu_ge+0x30;
  temp_humidity[0]=(char)shidu_shi+0x30;
  temp_humidity[1]=(char)shidu_ge+0x30;
  DelayMS(1000); //延時
  return temp_humidity;
}
//temp_humidity[2]和temp_humidity[3]溫度char表示
//temp_humidity[0]和temp_humidity[1]溼度char表示

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章