基于HAL库,读取DHT11传感器温湿度数据的代码
时间: 2024-05-03 09:16:36 浏览: 83
以下是基于HAL库的DHT11传感器读取温湿度数据的示例代码:
```
#include "stm32f4xx_hal.h"
#define DHT11_PORT GPIOA
#define DHT11_PIN GPIO_PIN_0
void DHT11_Start(void);
uint8_t DHT11_Check(void);
uint8_t DHT11_ReadBit(void);
uint8_t DHT11_ReadByte(void);
int main(void)
{
HAL_Init();
__HAL_RCC_GPIOA_CLK_ENABLE();
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.Pin = DHT11_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(DHT11_PORT, &GPIO_InitStruct);
while (1)
{
DHT11_Start();
if (DHT11_Check() == 0)
{
uint8_t humidity_int = DHT11_ReadByte();
uint8_t humidity_dec = DHT11_ReadByte();
uint8_t temperature_int = DHT11_ReadByte();
uint8_t temperature_dec = DHT11_ReadByte();
uint8_t check_sum = DHT11_ReadByte();
if (humidity_int + humidity_dec + temperature_int + temperature_dec == check_sum)
{
float humidity = humidity_int + humidity_dec / 10.0f;
float temperature = temperature_int + temperature_dec / 10.0f;
// 处理温湿度数据
}
}
HAL_Delay(2000);
}
}
void DHT11_Start(void)
{
HAL_GPIO_WritePin(DHT11_PORT, DHT11_PIN, GPIO_PIN_RESET);
HAL_Delay(18);
HAL_GPIO_WritePin(DHT11_PORT, DHT11_PIN, GPIO_PIN_SET);
HAL_Delay(40);
GPIO_InitStruct.Pin = DHT11_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(DHT11_PORT, &GPIO_InitStruct);
}
uint8_t DHT11_Check(void)
{
uint8_t response = 0;
uint16_t time_out = 0xFFFF;
while (HAL_GPIO_ReadPin(DHT11_PORT, DHT11_PIN) == GPIO_PIN_SET)
{
time_out--;
if (time_out == 0)
{
return 1;
}
}
time_out = 0xFFFF;
while (HAL_GPIO_ReadPin(DHT11_PORT, DHT11_PIN) == GPIO_PIN_RESET)
{
time_out--;
if (time_out == 0)
{
return 1;
}
}
time_out = 0xFFFF;
while (HAL_GPIO_ReadPin(DHT11_PORT, DHT11_PIN) == GPIO_PIN_SET)
{
time_out--;
if (time_out == 0)
{
return 1;
}
}
return response;
}
uint8_t DHT11_ReadBit(void)
{
uint8_t response = 0;
uint16_t time_out = 0xFFFF;
while (HAL_GPIO_ReadPin(DHT11_PORT, DHT11_PIN) == GPIO_PIN_RESET)
{
time_out--;
if (time_out == 0)
{
return 1;
}
}
time_out = 0xFFFF;
while (HAL_GPIO_ReadPin(DHT11_PORT, DHT11_PIN) == GPIO_PIN_SET)
{
time_out--;
if (time_out == 0)
{
return 1;
}
}
if (time_out < 100)
{
response = 1;
}
return response;
}
uint8_t DHT11_ReadByte(void)
{
uint8_t byte = 0;
for (uint8_t i = 0; i < 8; i++)
{
byte <<= 1;
byte |= DHT11_ReadBit();
}
return byte;
}
```
代码中,首先定义了DHT11传感器的GPIO引脚,然后在`main()`函数中初始化GPIO引脚,并循环读取温湿度数据。在每次读取时,调用`DHT11_Start()`函数进行DHT11传感器的开始信号发送,然后调用`DHT11_Check()`函数检查DHT11传感器的响应是否正确。如果响应正确,则调用`DHT11_ReadByte()`函数分别读取温度和湿度数据,并计算校验和进行校验。最后,在温湿度数据有效的情况下,可以将温湿度数据进行处理。
`DHT11_Start()`函数中,首先将DHT11引脚拉低18ms,然后拉高40us。接着,将DHT11引脚设为输入模式,并开启上拉电阻。
`DHT11_Check()`函数中,通过等待DHT11引脚由高电平变为低电平,再等待DHT11引脚由低电平变为高电平,最后等待DHT11引脚的响应信号结束,判断DHT11传感器的响应是否正确。
`DHT11_ReadBit()`函数中,等待DHT11引脚由低电平变为高电平,再等待DHT11引脚的高电平持续时间,判断读取到的数据是否为1。
`DHT11_ReadByte()`函数中,循环读取8位数据,并通过位移运算和按位或运算将各位数据组合成一个字节。
阅读全文