#define DATA_IN DDRE &= ~(1 << PE0)
#define DATA_OUT DDRE |= (1 << PE0)
#define DATA_CLR PORTE &= ~(1 << PE0)
#define DATA_SET PORTE |= (1 << PE0)
#define DATA_READ PINE & (1 <<PE0)
char DHT_byte(unsigned char *p)
{
unsigned char j,time_flag,DHT_byte_value=0,temp;
for(j=0;j<8;j++)
{
time_flag=2;
while((!(DATA_READ))&&time_flag++);
if(time_flag==1) //超时终止
{
*p=0x01;
break;
}
delay_us(40);
temp=0;
if(DATA_READ)temp=1;
time_flag=2;
while((DATA_READ)&&time_flag++);
if(time_flag==1)
{
*p=0x01;
break;
}
DHT_byte_value<<=1;
DHT_byte_value|=temp;
}
return DHT_byte_value;
}
//--------------------------------
//-----温湿度读取子程序 ------------
//--------------------------------
//----湿度高8位== DHT_value[0]-----
//----湿度低8位== DHT_value[1]-----
//----温度高8位== DHT_value[2]------
//----温度低8位== DHT_value[3]------
//----校验 8位 == DHT_value[4]-----
//--------------------------------
void DHT_read(unsigned char *p)
{
unsigned char i,time_flag,DHT_v_temp[5],temp1=0;
//主机拉低18ms
DATA_OUT;
DATA_CLR;
delay_ms(18);
//设置为输入,总线由上拉电阻拉高主机延时20-40us
DATA_IN;
DATA_SET;
delay_us(40);
if(DATA_READ) time_flag=1;
while(!(DATA_READ))
{
time_flag=2;
while((!(DATA_READ))&&time_flag++); //
if(time_flag==1) break;
time_flag=2;
while((DATA_READ)&&time_flag++);
if(time_flag==1) break;
for(i=0;i<5;i++)
{
DHT_v_temp[i]=DHT_byte(&time_flag);
if(time_flag==1)break;
if(i<4) temp1 += DHT_v_temp[i];
}
}
DATA_IN;
DATA_SET;
//数据校验
if(temp1==DHT_v_temp[4])
{
for(i=0;i<5;i++)
{
*(p+i)=DHT_v_temp[i];
}
}
}
|