写一段STM32驱动DHT11的代码
时间: 2023-03-27 17:01:37 浏览: 70
以下是一段STM32驱动DHT11的代码,仅供参考:
#include "stm32f10x.h"
#include "dht11.h"
void DHT11_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_SetBits(GPIOB, GPIO_Pin_12);
}
void DHT11_Start(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_ResetBits(GPIOB, GPIO_Pin_12);
delay_us(18000);
GPIO_SetBits(GPIOB, GPIO_Pin_12);
delay_us(20);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
u8 DHT11_Read_Bit(void)
{
while (GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_12) == RESET);
delay_us(40);
if (GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_12) == SET)
return 1;
else
return ;
}
u8 DHT11_Read_Byte(void)
{
u8 i, j, dat = ;
for (j = ; j < 8; j++)
{
i = DHT11_Read_Bit();
dat <<= 1;
dat |= i;
}
return dat;
}
u8 DHT11_Read_Data(u8 *temp, u8 *humi)
{
u8 buf[5], i;
DHT11_Start();
if (GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_12) == RESET)
{
while (GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_12) == RESET);
while (GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_12) == SET);
for (i = ; i < 5; i++)
buf[i] = DHT11_Read_Byte();
if ((buf[] + buf[1] + buf[2] + buf[3]) == buf[4])
{
*humi = buf[];
*temp = buf[2];
}
return 1;
}
else
return ;
}