|
我把AM2301连接到了普中stm326806L的PG11上,能接收到应答信号,但是到了判断位数据0、1的时候就出错了,索性就只检测高低电平,发现AM2301_Read_Bit函数只读到高电平,但是示波器有波形,是啥子问题
#define AM2301_PORT GPIOG
#define AM2301_PIN (GPIO_Pin_11)
#define AM2301_PORT_RCC RCC_APB2Periph_GPIOG
#define AM2301_DQ_OUT PGout(11)
#define AM2301_DQ_IN PGin(11)
C文件:
#include "AM2301.h"
#include "SysTick.h"
#include "usart.h"
void AM2301_IO_IN(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin=AM2301_PIN;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IPU;
GPIO_Init(AM2301_PORT,&GPIO_InitStructure);
}
void AM2301_IO_OUT(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin=AM2301_PIN;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;
GPIO_Init(AM2301_PORT,&GPIO_InitStructure);
}
void AM2301_Reset(void)
{
AM2301_IO_OUT(); //SET OUTPUT
AM2301_DQ_OUT=0; //拉低DQ
delay_ms(3); //拉低
AM2301_DQ_OUT=1; //DQ=1
delay_us(30); //主机拉高20~40us
}
//1表示失败
u8 AM2301_Check(void)
{
u8 retry=0;
AM2301_IO_IN();//SET INPUT
while (AM2301_DQ_IN&&retry<85)//DHT11会拉低40~80us
{
retry++;
delay_us(1);
}
if(AM2301_DQ_IN==0)printf("输出低电平\r\n");
if(retry>=85)return 1;
else retry=0;
while (!AM2301_DQ_IN&&retry<85)//DHT11拉低后会再次拉高40~80us
{
retry++;
delay_us(1);
}
if(AM2301_DQ_IN==1)printf("输出高电平\r\n");
if(retry>=85)return 1;
else return 0;
}
//Return the value that has been read
/********************************************************************
这个地方读到的都是1
********************************************************************/
u8 AM2301_Read_Bit(void)
{
u16 retry=0;
while(AM2301_DQ_IN&&retry<1000)
{
retry++;
delay_us(1);
}
if(retry>=1000)printf("只输出了高电平时间到了才跳出\r\n");
else printf("检测到低电平跳出的循环");
delay_us(50);
while(!AM2301_DQ_IN);
delay_us(40);
if(AM2301_DQ_IN)return 1;
else return 0;
}
u8 AM2301_Read_Byte(void)
{
u8 i,dat;
dat=0;
for (i=0;i<8;i++)
{
dat<<=1;
dat|=AM2301_Read_Bit();
}
return dat;
}
//0 is normal
u8 AM2301_Read_Data(u16 *temp,u16 *humi)
{
u8 buf[5];
u8 i,x,y,u,v;
// AM2301_Reset();
if(AM2301_Check()==0)
{
printf("到达AM2301读数据函数\r\n");
for(i=0;i<5;i++)//读取40位数据
{
buf[i]=AM2301_Read_Byte();
printf("%d\r\n",buf[2]);
}
// 接收的都是高电平校验无法通过
// if((buf[0]+buf[1]+buf[2]+buf[3])==buf[4])
// {
printf("校验\r\n");
x=buf[0];
y=buf[1];
x=(x*256+y);
*humi=x;
printf("湿度传送完成\r\n");
u=buf[2];
v=buf[3];
u=(u*256+v);
*temp=u;
printf("温度传送完成\r\n");
// }
}else return 1;
return 0;
}
u8 AM2301_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(AM2301_PORT_RCC,ENABLE);
GPIO_InitStructure.GPIO_Pin=AM2301_PIN;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;
GPIO_Init(AM2301_PORT,&GPIO_InitStructure);
GPIO_SetBits(GPIOG,GPIO_Pin_11);
delay_ms(3000);
AM2301_Reset();
return AM2301_Check();
}
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
|