DHT22

DHT22.c
#include "DHT22.h"
#include "delay.h"
#include    

//Reset DHT11
void DHT22_Rst(void)	   
{                 
		DHT22_IO_OUT(); 	//SET OUTPUT
    DHT22_DQ_OUT=0; 	//GPIOA.0=0
    delay_ms(30);    	//Pull down Least 800us
    DHT22_DQ_OUT=1; 	//GPIOA.0=1 
		delay_us(30);     	//Pull up 20~40us
}

u8 DHT22_Check(void) 	   
{   
	u8 retry=0;
	DHT22_IO_IN();//SET INPUT	 
    while (DHT22_DQ_IN&&retry<100)//DHT22 Pull down 40~80us
	{
		retry++;
		delay_us(1);
	};	 
	if(retry>=100)
	{
		return 1;	
	}
	else 
		retry=0;
    while (!DHT22_DQ_IN&&retry<100)//DHT22 Pull up 40~80us
	{
		retry++;
		delay_us(1);
	};
	if(retry>=100)
  {
		return 1;//chack error	
				
  }        
	return 0;
}

u8 DHT22_Read_Bit(void) 			 
{
 	u8 retry=0;
	while(DHT22_DQ_IN&&retry<100)//wait become Low level
	{
		retry++;
		delay_us(1);
	}
	retry=0;
	while(!DHT22_DQ_IN&&retry<100)//wait become High level
	{
		retry++;
		delay_us(1);
	}
	delay_us(40);//wait 40us
	if(DHT22_DQ_IN)
		return 1;
	else 
		return 0;		   
}

u8 DHT22_Read_Byte(void)    
{        
    u8 i,dat;
    dat=0;
	for (i=0;i<8;i++) 
	{
   		dat<<=1; 
	    dat|=DHT22_Read_Bit();
    }						    
    return dat;
}

u8 DHT22_Read_Data(u16 *temperature,u16 *humidity)    
{        
 	u8 buf[5];
	u8 i;
	DHT22_Rst();
	if(DHT22_Check()==0)
	{
		for(i=0;i<5;i++)
		{
			buf[i]=DHT22_Read_Byte();
		}
		*humidity=((buf[0]*256)+buf[1])/10;
		*temperature=((buf[2]*256)+buf[3])/10;
	}
	else 
	{
		return 1;
	}
	return 0;	    
}
	 
u8 DHT22_Init(void)
{	 
 	GPIO_InitTypeDef  GPIO_InitStructure;
 	
 	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);	 
	
 	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;				 
 	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; 		 
 	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
 	GPIO_Init(GPIOA, &GPIO_InitStructure);				 
 	GPIO_SetBits(GPIOA,GPIO_Pin_0);						 
			    
	DHT22_Rst();  
	return DHT22_Check();
} 
DHT22.h
#ifndef __DHT22_H
#define __DHT22_H 
#include "sys.h"  
 
//Set GPIO Direction
#define DHT22_IO_IN()  {GPIOA->CRL&=0XFFFF0FFF;GPIOA->CRL|=8<<12;}	//PA3
#define DHT22_IO_OUT() {GPIOA->CRL&=0XFFFF0FFF;GPIOA->CRL|=3<<12;}	//PA3
											   
#define	DHT22_DQ_OUT PAout(3) 
#define	DHT22_DQ_IN  PAin(3)   


u8 DHT22_Init(void); //Init DHT22
u8 DHT22_Read_Data(u16 *temperature,u16 *humidity); //Read DHT22 Value
u8 DHT22_Read_Byte(void);//Read One Byte
u8 DHT22_Read_Bit(void);//Read One Bit
u8 DHT22_Check(void);//Chack DHT22
void DHT22_Rst(void);//Reset DHT22    
#endif
main.c
DHT22_Read_Data(&temperature,&humidity);


你可能感兴趣的:(模块开发)