DHT22(AM2303)的AVR的GCC例程,运行已经1年,非常稳定
#include<avr/io.h>
#include<util/delay.h>
#include<avr/interrupt.h>
//#include"DHT22.h"
#include"UART.H"
//
//端口设定
#define DHT22_PIN PA0
#define DDR_DHT22 DDRA
#define PORT_DHT22 PORTA
#define PIN_DHT22 PINA
//端口操作宏定义
#define DHT22_PIN_SET_OUT() DDR_DHT22|=(1<<DHT22_PIN)
#define DHT22_PIN_SET_IN() DDR_DHT22&=~(1<<DHT22_PIN)
#define DHT22_WR1() PORT_DHT22|=(1<<DHT22_PIN)
#define DHT22_WR0() PORT_DHT22&=~(1<<DHT22_PIN)
#define R_DHT22() PIN_DHT22&(1<<DHT22_PIN)
unsigned char star=0 ;
//
unsigned char FLAG , temp , comdata ;
//
unsigned char T_data_H_temp , T_data_L_temp , RH_data_H_temp , RH_data_L_temp , checkdata_temp ;
//
void COM(void)
{
unsigned char i;
for(i=0;i<8;i++)
{
FLAG=2;
while((!(R_DHT22()))&&FLAG++);
if(FLAG==1)break;
_delay_us(10);
_delay_us(10);
_delay_us(10);
_delay_us(10);
temp=0;
if(R_DHT22())temp=1;
FLAG=2;
while((R_DHT22())&&FLAG++);
//超时则跳出for循环
if(FLAG==1)break;
//判断数据位是0还是1
// 如果高电平高过预定0高电平值则数据位为 1
comdata<<=1;
comdata|=temp; //0
}//rof
}
//
void RH(void)
{
//主机拉低18ms
DHT22_PIN_SET_OUT() ;
DHT22_WR0();
_delay_ms(1);
DHT22_PIN_SET_IN();
DHT22_WR1();
//总线由上拉电阻拉高 主机延时20us
_delay_us(10);
_delay_us(10);
_delay_us(10);
_delay_us(10);
//主机设为输入 判断从机响应信号
//P2_0=1;
//判断从机是否有低电平响应信号 如不响应则跳出,响应则向下运行
// if(!P2_0) //T !
if(R_DHT22())FLAG=1;
while(!(R_DHT22()))
{
FLAG=2;
//判断从机是否发出 80us 的低电平响应信号是否结束
//while((!P2_0)&&U8FLAG++);
while((!(R_DHT22()))&&FLAG++);
if(FLAG==1)break;
FLAG=2;
//判断从机是否发出 80us 的高电平,如发出则进入数据接收状态
//while((P2_0)&&U8FLAG++);
while((R_DHT22())&&FLAG++);
if(FLAG==1)break;
//数据接收状态
COM();
if(FLAG==1)break;
T_data_H_temp=comdata;
COM();
if(FLAG==1)break;
T_data_L_temp=comdata;
COM();
if(FLAG==1)break;
RH_data_H_temp=comdata;
COM();
if(FLAG==1)break;
RH_data_L_temp=comdata;
COM();
if(FLAG==1)break;
checkdata_temp=comdata;
break;
}//while
//P2_0=1;
DHT22_PIN_SET_IN();
DHT22_WR1();
//数据校验
/*
temp=(T_data_H_temp+T_data_L_temp+RH_data_H_temp+RH_data_L_temp);
if(U8temp==U8checkdata_temp)
{
U8RH_data_H=U8T_data_H_temp;
U8RH_data_L=U8T_data_L_temp;
U8T_data_H=U8RH_data_H_temp;
U8T_data_L=U8RH_data_L_temp;
U8checkdata=U8checkdata_temp;
}//fi
*/
DHT22_PIN_SET_IN();
DHT22_WR1();
}
//
int main(void)
{
//unsigned char data[10]={0};
//unsigned char i;
Init_Uart();
asm("sei") ;
UART_Transmit(0x34) ;
DHT22_PIN_SET_IN();
DHT22_WR1();
while(1)
{
if(star>0)//串口接收到一个非0数字
{
asm("cli") ;
RH();
UART_Transmit(T_data_H_temp) ;
UART_Transmit(T_data_L_temp) ;
UART_Transmit(RH_data_H_temp) ;
UART_Transmit(RH_data_L_temp) ;
UART_Transmit(checkdata_temp) ;
asm("sei");
star = 0 ;
}
//DHT22_Start();
_delay_us(50);
_delay_ms(50);
_delay_ms(50);
_delay_ms(50);
}
}
/****************************************************
UART中断函数
****************************************************/
ISR(USART_RXC_vect)
{
asm("cli");//关中断
star = UDR;//读取 暂时无用
asm("sei");//开中断
return ;
}
//
|