[C] syntaxhighlighter_viewsource syntaxhighlighter_copycode
#include "sys.h"
#include "delay.h"
#include "key.h"
#include "usart.h"
#include "LED.H"
u8 temperatures[2],humiditys[2];//¶¨òåζè¡¢êa¶è±äá¿
u8 flag=1;
//¸′λDHT11
void DHT11_Rst()
{
key_mod_out();
key_out=0;
delay_ms(20);
key_out=1;
delay_us(30);//à-¸ß30us£¬μè′yDHT11Ïìó|
}
//¼ì2aDHT11êÇ·ñ¿ÕÏD
u8 DHT11_Check()
{
u8 wait_time=0;
DHT11_Rst();
key_mod_in();
while(key_in&&wait_time<100)
{
delay_us(1);
wait_time++;
}
if(wait_time>=100)
return 0;
else
wait_time=0;
while(!key_in&&wait_time<100)
{
delay_us(1);
wait_time++;
}
if(wait_time>=100)
return 0;
return 1;
}
//¶áò»¸öλ
u8 read_bit()
{
u8 wait_time=0;
while(key_in&&wait_time<100)//μè′y±äμí
{
delay_us(1);
wait_time++;
}
wait_time=0;
while(!key_in&&wait_time<100)//μè′y±ä¸ß
{
delay_us(1);
wait_time++;
}
delay_us(40);
if(key_in)
return 1;
else
return 0;
}
//¶á3öò»¸ö×Ö½úμÄêy¾Y
u8 read_byte()
{
u8 i,val=0;
for(i=0;i<8;i++)
{
val<<=1;
if(read_bit())
{
val|=0x01;
}
}
return val;
}
//¶á3öÎÂêa¶èÖμ
u8 read_data(u8 *a,u8 *b)
{
u8 i,buf[5],temp=0;
if(DHT11_Check())
{
for(i=0;i<5;i++)
{
buf=read_byte();
}
for(i=0;i<4;i++)
{
temp+=buf;
}
if(temp==buf[4])
{
//ζèÖμ
a[0]=buf[2];
a[1]=buf[3];
//êa¶èÖμ
b[0]=buf[0];
b[1]=buf[1];
}
else
return 0;
}
else
return 0;
return 1;
}
int main(void)
{
float temperature,humidity;
delay_init(168);
uart_init(115200);
LED_Init();
key_init();
if(DHT11_Check())
{
printf("ok");
}
else
printf("error");
printf("\r\n");
while(1)
{
KEY_Scan(0);//μ÷óð′¼üé¨Ãèoˉêy£¬¸Ä±äflagÖ죬èôflag=1,êä3öéãêÏζ裬flag=2,êä3ö»aêÏζ裬flag=3,êä3ö¿aêÏζè
delay_ms(2000);//ÿ2Ãë¶áè¡ò»′ÎÎÂêa¶è
if(temperature<19.0)
{
LED0=0;
}//èôζèμíóú19¶è£¬LED0áᣬ·ñÔòϨÃe
else
{
LED0=1;
}
if(read_data(temperatures,humiditys))
{
temperature=temperatures[0]+0.0039*temperatures[1];
humidity=humiditys[0]+0.0039*humiditys[1];
if(flag==1)
{
printf("temperature: %.2féãê϶è",temperature);
}
else if(flag==2)
{
printf("temperature: %.2f»aê϶è",temperature*1.8+32);
}
else if(flag==3)
{
printf("temperature: %.2f¿aê϶è",temperature+273);
}
printf("\r\n");
printf("humidity: °ù·ÖÖ®%.2f",humidity);
printf("\r\n");
}
else printf("unknow error\r\n");
}
}