stm32使用HAL_UART_Transmit()函数将收到的dht11数据通过串口发送数据到HC-05
时间: 2024-01-28 12:39:01 浏览: 74
stm32串口发送
5星 · 资源好评率100%
首先需要在代码中初始化串口和DHT11。假设串口使用USART1,DHT11连接到PA0引脚。
```
UART_HandleTypeDef huart1;
void MX_USART1_UART_Init(void)
{
huart1.Instance = USART1;
huart1.Init.BaudRate = 9600;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
}
void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
__HAL_RCC_GPIOA_CLK_ENABLE();
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_0, GPIO_PIN_RESET);
GPIO_InitStruct.Pin = GPIO_PIN_0;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}
void DHT11_Start(void)
{
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_0, GPIO_PIN_RESET);
HAL_Delay(18);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_0, GPIO_PIN_SET);
HAL_Delay(40);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_0, GPIO_PIN_RESET);
}
uint8_t DHT11_Check_Response(void)
{
uint8_t Response = 0;
HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0);
HAL_Delay(10);
if (!HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0))
{
HAL_Delay(80);
if (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0))
Response = 1;
}
while (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0))
;
return Response;
}
uint8_t DHT11_Read_Data(void)
{
uint8_t i, j;
for (j = 0; j < 8; j++)
{
while (!HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0))
;
HAL_Delay(40);
if (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0) == 0)
{
i &= ~(1 << (7 - j));
}
else
{
i |= (1 << (7 - j));
while (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0))
;
}
}
return i;
}
```
然后在主函数中,读取DHT11数据并发送到HC-05。
```
int main(void)
{
uint8_t hum_int, hum_dec, temp_int, temp_dec, check_sum;
MX_GPIO_Init();
MX_USART1_UART_Init();
while (1)
{
DHT11_Start();
if (DHT11_Check_Response())
{
hum_int = DHT11_Read_Data();
hum_dec = DHT11_Read_Data();
temp_int = DHT11_Read_Data();
temp_dec = DHT11_Read_Data();
check_sum = DHT11_Read_Data();
if ((hum_int + hum_dec + temp_int + temp_dec) == check_sum)
{
char data[50];
sprintf(data, "Humidity: %d.%d%%, Temperature: %d.%dC\r\n", hum_int, hum_dec, temp_int, temp_dec);
HAL_UART_Transmit(&huart1, (uint8_t *)data, strlen(data), HAL_MAX_DELAY);
}
}
HAL_Delay(2000);
}
}
```
在上面的代码中,我们使用sprintf()函数将DHT11数据格式化为字符串,然后使用HAL_UART_Transmit()函数将其发送到HC-05。请注意,我们将字符串转换为uint8_t型数组,并计算它的长度。在HAL_UART_Transmit()函数中,我们使用HAL_MAX_DELAY作为超时参数,以确保数据完全发送。
阅读全文