#include "dht11.h" #include "protocol.h" #include "lcd.h" #include "string.h" #include <stdio.h> #include "gpio.h" #include "usart.h" #define DHT11_DATA_LOW_TIMEOUT 80 #define DHT11_DATA_HIGH_TIMEOUT 90 #define DHT11_RESPONSE_TIMEOUT 40 #define DHT11_BIT_TIMEOUT 60 DHT11_StatusTypeDef DHT11_ReadData(DHT11_Data_TypeDef* data) { uint8_t buffer[5] = {0}; uint8_t i, j; uint32_t count; // 发送开始信号 HAL_GPIO_WritePin(GPIOB, GPIO_PIN_8, GPIO_PIN_SET); HAL_Delay(18); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_8, GPIO_PIN_RESET); // 等待DHT11响应 count = 0; while (HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_8) == GPIO_PIN_RESET) { count++; if (count > DHT11_RESPONSE_TIMEOUT) { return DHT11_ERROR; } HAL_Delay(1); } count = 0; while (HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_8) == GPIO_PIN_SET) { count++; if (count > DHT11_RESPONSE_TIMEOUT) { return DHT11_ERROR; } HAL_Delay(1); } // 读取40位数据 for (i = 0; i < 40; i++) { count = 0; while (HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_8) == GPIO_PIN_RESET) { count++; if (count > DHT11_DATA_LOW_TIMEOUT) { return DHT11_ERROR; } } count = 0; while (HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_8) == GPIO_PIN_SET) { count++; if (count > DHT11_DATA_HIGH_TIMEOUT) { return DHT11_ERROR; } } buffer[i / 8] <<= 1; if (count > DHT11_BIT_TIMEOUT) { buffer[i / 8] |= 0x01; } } // 验证数据是否正确 if (buffer[4] != (buffer[0] + buffer[1] + buffer[2] + buffer[3])) { return DHT11_ERROR; } // 解析数据 data->humidity = buffer[0]; data->temp_int = buffer[2]; data->temp_dec = buffer[3]; return DHT11_OK; } void text_func_1() { DHT11_Data_TypeDef data; DHT11_ReadData(&data); printf("-->"); printf("%d.%c %d%%",data.temp_int, data.temp_dec, data.humidity); HAL_Delay(1000); if (DHT11_ReadData(&data) == DHT11_OK){ char str[16]; sprintf(str, "T:%d.%dC H:%d%%", data.temp_int, data.temp_dec, data.humidity); HAL_UART_Transmit(&huart1, (uint8_t*)str, strlen(str), HAL_MAX_DELAY); HAL_Delay(1000); } }改错
时间: 2024-03-13 17:44:53 浏览: 143
代码中需要修改的地方:
1. 在 `DHT11_ReadData` 函数中,`buffer[i / 8]` 需要先清零再左移,否则可能导致结果错误。
修改前:`buffer[i / 8] <<= 1;`
修改后:`buffer[i / 8] = 0; buffer[i / 8] |= 0x01 << (7 - (i % 8));`
2. 在 `text_func_1` 函数中,需要判断 `DHT11_ReadData` 函数返回值是否为 `DHT11_OK`,如果不是,则不执行后面的代码。
修改前:
```
DHT11_ReadData(&data);
printf("-->");
printf("%d.%c %d%%",data.temp_int, data.temp_dec, data.humidity);
HAL_Delay(1000);
if (DHT11_ReadData(&data) == DHT11_OK){
char str[16];
sprintf(str, "T:%d.%dC H:%d%%", data.temp_int, data.temp_dec, data.humidity);
HAL_UART_Transmit(&huart1, (uint8_t*)str, strlen(str), HAL_MAX_DELAY);
HAL_Delay(1000);
}
```
修改后:
```
if (DHT11_ReadData(&data) == DHT11_OK){
printf("-->");
printf("%d.%c %d%%",data.temp_int, data.temp_dec, data.humidity);
HAL_Delay(1000);
char str[16];
sprintf(str, "T:%d.%dC H:%d%%", data.temp_int, data.temp_dec, data.humidity);
HAL_UART_Transmit(&huart1, (uint8_t*)str, strlen(str), HAL_MAX_DELAY);
HAL_Delay(1000);
}
```
阅读全文