am2302.c
#include "am2302.h" #include "SysTick.h" void AM2302_Rst(void) {
AM2302_IO_OUT(); //SET OUTPUT AM2302_DQ_OUT=0; //拉低DQ delay_ms(20); //拉低至少18ms AM2302_DQ_OUT=1; //DQ=1 delay_us(30); ///主机拉高20~40us } u8 AM2302_Check(void) {
u8 retry=0; AM2302_IO_IN(); while (AM2302_DQ_IN&&retry<100)//拉低40~80us {
retry ; delay_us(1); }; if(retry>=100)return 1; else retry=0; while (!AM2302_DQ_IN&&retry<100)///再次拉高40~80us {
retry ; delay_us(1); }; if(retry>=100)return 1; return 0;
}
u8 AM2302_Read_Bit(void)
{
u8 retry=0;
while(AM2302_DQ_IN&&retry<100)//等待变为低电平
{
retry++;
delay_us(1);
}
retry=0;
while(!AM2302_DQ_IN&&retry<100)//等待变高电平
{
retry++;
delay_us(1);
}
delay_us(40);//等待40us
if(AM2302_DQ_IN)return 1;
else return 0;
}
u8 AM2302_Read_Byte(void)
{
u8 i,dat;
dat=0;
for (i=0;i<8;i++)
{
dat<<=1;
dat|=AM2302_Read_Bit();
}
return dat;
}
u8 AM2302_Read_Data(u16 *temp)
{
u8 buf[5];
u8 i;
AM2302_Rst();
if(AM2302_Check()==0)
{
for(i=0;i<5;i++)//读取40位数据
{
buf[i]=AM2302_Read_Byte();
}
if((unsigned char)(buf[0]+buf[1]+buf[2]+buf[3])==buf[4])
{
for(i=0;i<4;i++)
{
*temp=buf[i];
temp++;
}
return 0;
}
}
else
return 1;
}
u8 AM2302_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);//使能时钟
GPIO_Init(GPIOD, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 ;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;//普通输出模式
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;//推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;//上拉
AM2302_Rst();
return AM2302_Check();
}
am2302.h
#ifndef __AM2302_H
#define __AM2302_H
#include "SysTick.h"
#define AM2302_IO_IN() {
GPIOD->MODER&=~(3<<(6*2));GPIOD->MODER|=0<<6*2;} //输入模式
#define AM2302_IO_OUT() {
GPIOD->MODER&=~(3<<(6*2));GPIOD->MODER|=1<<6*2;} //输出模式
#define AM2302_DQ_OUT PDout(6)
#define AM2302_DQ_IN PDin(6)
u8 AM2302_Init(void);
u8 AM2302_Read_Data(u16 *temp);
u8 AM2302_Read_Byte(void);
u8 AM2302_Read_Bit(void);
u8 AM2302_Check(void);
void AM2302_Rst(void);
#endif