新手入门
- 积分
- 16
- 金钱
- 16
- 注册时间
- 2021-8-6
- 在线时间
- 4 小时
|
1金钱
#include "dht11.h"
#include "delay.h"
#include "usart.h"
uint8_t dat[5]={0,0,0,0,0};
uint16_t sum;
void DHT11_Port_Output(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE);//使能GPIOB时钟
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;//设置PB6为输出
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;//普通输出模式
GPIO_InitStructure.GPIO_OType=GPIO_OType_PP;//设置为推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;//100MHz
GPIO_InitStructure.GPIO_PuPd =GPIO_PuPd_UP;//上拉
GPIO_Init(GPIOF, &GPIO_InitStructure);//初始化GPIO
}
void DHT11_Port_Input(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE);//使能GPIOB时钟
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;//设置PB6为输入
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;//普通输入
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;//100MHz
GPIO_Init(GPIOF, &GPIO_InitStructure);//初始化GPIO
}
uint8_t DHT11_Read_Byte(void)
{
uint8_t temp;
uint8_t ReadDat=0;
uint8_t i;
uint16_t retry=0;//防止PB5没有收到高电平卡死在程序
for(i=0;i<8;i++)
{
while(GPIO_ReadInputDataBit(GPIOF,GPIO_Pin_6)==0 && retry<100 )
{
delay_us(1);
retry++;
}
if(retry==100)
{
printf("retry:%d\r\n",retry);
return 0;
}
retry=0;
delay_us(30);
if(GPIO_ReadInputDataBit(GPIOF,GPIO_Pin_6)==0)
{temp=0;}
if(GPIO_ReadInputDataBit(GPIOF,GPIO_Pin_6)==1)
{temp=1;}
while(GPIO_ReadInputDataBit(GPIOF,GPIO_Pin_6)==1 && retry<100)
{
delay_us(1);
retry++;
}
retry=0;
printf("temp:%d\r\n",temp);
ReadDat<<=1;
ReadDat|=temp;
printf("ReadDat:%d\r\n",ReadDat);
}
return ReadDat;
}
uint8_t DHT_Read(u8 *temp,u8 *html)
{
uint8_t retry=0;
uint8_t i;
DHT11_Port_Output();
GPIO_ResetBits(GPIOF,GPIO_Pin_6);
delay_ms(18);
GPIO_SetBits(GPIOF,GPIO_Pin_6);
delay_us(40);
DHT11_Port_Input();
if(GPIO_ReadInputDataBit(GPIOF,GPIO_Pin_6)==0)
{
while(GPIO_ReadInputDataBit(GPIOF,GPIO_Pin_6)==0 && retry<100 )
{
delay_us(1);
retry++;
}
retry=0;
while(GPIO_ReadInputDataBit(GPIOF,GPIO_Pin_6)==1 && retry<100 )
{
delay_us(1);
retry++;
}
retry=0;
for(i=0;i<5;i++)
{
dat[i]= DHT11_Read_Byte();
}
delay_us(50);
}
sum=dat[0]+dat[1]+dat[2]+dat[3];
if(dat[4]==(u8)(sum) )
{
*temp=dat[0];
*html=dat[2];
printf("html:%d\r\n",&html);
return 1;
}
else
return 0;
}
这是我的DHT11的代码,问题是我用串口测试 ,时序我觉得没有问题,首先DHT11响应了我一个低电平,但是后面发的数据都是高电平,就很奇怪。希望各位大神给我看看代码。
|
-
|