写出基于stm32,DHT11数据通过HC-05蓝牙与安卓app通信的代码,并且附加注释
时间: 2024-05-25 20:16:09 浏览: 149
以下是基于STM32,DHT11数据通过HC-05蓝牙与安卓app通信的代码,已加入注释。
注:本代码使用的是HAL库,并且需要自己定义相应的USART和GPIO的引脚号,以及DHT11的引脚号。
#include "stm32f1xx_hal.h"
//定义蓝牙串口通信的USART
UART_HandleTypeDef huart2;
//定义DHT11引脚号
#define DHT11_PORT GPIOA
#define DHT11_PIN GPIO_PIN_1
//定义蓝牙串口通信的引脚号
#define BT_TX_PIN GPIO_PIN_2
#define BT_RX_PIN GPIO_PIN_3
#define BT_GPIO_PORT GPIOA
//定义接收蓝牙数据的缓冲区
uint8_t BT_RxBuffer[1];
//定义发送给蓝牙的数据
uint8_t BT_TxBuffer[5];
//定义DHT11读取到的温度和湿度
float temperature = 0;
float humidity = 0;
//定义DHT11数据读取函数
void DHT11_ReadData(void)
{
uint8_t i, j, byte;
uint8_t data[5] = { 0, 0, 0, 0, 0 };
//发送起始信号
HAL_GPIO_WritePin(DHT11_PORT, DHT11_PIN, GPIO_PIN_RESET);
HAL_Delay(20);
HAL_GPIO_WritePin(DHT11_PORT, DHT11_PIN, GPIO_PIN_SET);
//等待DHT11响应
while (HAL_GPIO_ReadPin(DHT11_PORT, DHT11_PIN) == GPIO_PIN_RESET);
while (HAL_GPIO_ReadPin(DHT11_PORT, DHT11_PIN) == GPIO_PIN_SET);
//读取DHT11数据
for (j = 0; j < 5; j++)
{
for (i = 0; i < 8; i++)
{
while (HAL_GPIO_ReadPin(DHT11_PORT, DHT11_PIN) == GPIO_PIN_RESET);
HAL_Delay(40);
if (HAL_GPIO_ReadPin(DHT11_PORT, DHT11_PIN) == GPIO_PIN_SET)
{
byte |= (1 << (7 - i));
}
while (HAL_GPIO_ReadPin(DHT11_PORT, DHT11_PIN) == GPIO_PIN_SET);
}
data[j] = byte;
byte = 0;
}
//计算温湿度
humidity = (data[0] * 256 + data[1]) / 10.0;
temperature = (data[2] * 256 + data[3]) / 10.0;
}
int main(void)
{
//初始化MCU
HAL_Init();
//初始化蓝牙串口通信
huart2.Instance = USART2;
huart2.Init.BaudRate = 9600;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
HAL_UART_Init(&huart2);
//初始化DHT11引脚
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.Pin = DHT11_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(DHT11_PORT, &GPIO_InitStruct);
HAL_GPIO_WritePin(DHT11_PORT, DHT11_PIN, GPIO_PIN_SET);
//初始化蓝牙引脚
GPIO_InitStruct.Pin = BT_TX_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(BT_GPIO_PORT, &GPIO_InitStruct);
GPIO_InitStruct.Pin = BT_RX_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(BT_GPIO_PORT, &GPIO_InitStruct);
//无限循环
while (1)
{
//读取DHT11数据
DHT11_ReadData();
//将温湿度数据转为字符串
sprintf((char*)BT_TxBuffer, "%.1f,%.1f", temperature, humidity);
//等待蓝牙连接
while (BT_RxBuffer[0] != 'C')
{
HAL_UART_Receive(&huart2, BT_RxBuffer, 1, HAL_MAX_DELAY);
}
//发送温湿度数据
HAL_UART_Transmit(&huart2, BT_TxBuffer, 5, HAL_MAX_DELAY);
//等待蓝牙接收完毕
while (BT_RxBuffer[0] != 'E')
{
HAL_UART_Receive(&huart2, BT_RxBuffer, 1, HAL_MAX_DELAY);
}
}
}
阅读全文