dht11通过uart通信协议接收数据的代码 keil
时间: 2023-06-26 21:05:36 浏览: 173
以下是基于Keil MDK的DHT11通过UART通信协议接收数据的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include "stm32f10x.h"
#include "uart.h"
#define DHT11_PORT GPIOA
#define DHT11_PIN GPIO_Pin_0
void delay_us(uint32_t us)
{
uint32_t i;
for(i = 0; i < us * 8; i++);
}
uint8_t read_byte(void)
{
uint8_t byte = 0;
uint8_t i;
for(i = 0; i < 8; i++)
{
while(GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == RESET); //等待高电平
delay_us(30); //等待30us
if(GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == SET) //如果为高电平,表示为1
{
byte |= (1 << (7 - i));
while(GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == SET); //等待低电平
}
}
return byte;
}
uint8_t dht11_receive_data(float *temperature, float *humidity)
{
uint8_t data[5] = {0};
uint8_t i;
uint8_t checksum = 0;
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Pin = DHT11_PIN;
GPIO_Init(DHT11_PORT, &GPIO_InitStructure); //设置为输出模式
GPIO_SetBits(DHT11_PORT, DHT11_PIN);
delay_us(500); //拉高至少500us
GPIO_ResetBits(DHT11_PORT, DHT11_PIN);
delay_us(18000); //拉低18ms
GPIO_SetBits(DHT11_PORT, DHT11_PIN);
delay_us(30); //等待30us
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(DHT11_PORT, &GPIO_InitStructure); //设置为上拉输入模式
if(GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == RESET) //DHT11响应
{
while(GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == RESET); //等待低电平结束
while(GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == SET); //等待高电平开始
for(i = 0; i < 5; i++)
{
data[i] = read_byte();
}
for(i = 0; i < 4; i++) //计算校验和
{
checksum += data[i];
}
if(checksum == data[4]) //校验和正确
{
*humidity = (float)data[0] + (float)data[1] / 10.0;
*temperature = (float)data[2] + (float)data[3] / 10.0;
return 0; //返回0表示读取成功
}
else //校验和错误
{
return 1; //返回1表示校验和错误
}
}
return 2; //返回2表示DHT11没有响应
}
int main()
{
float temperature, humidity;
uint8_t result;
uart_init(USART1, 115200); //初始化串口
printf("DHT11 Test\r\n");
while(1)
{
result = dht11_receive_data(&temperature, &humidity); //读取数据
if(result == 0) //读取成功
{
printf("Temperature: %.1fC, Humidity: %.1f%%\r\n", temperature, humidity);
}
else if(result == 1) //校验和错误
{
printf("Checksum error!\r\n");
}
else //DHT11没有响应
{
printf("No response!\r\n");
}
delay_us(2000000); //等待2s
}
}
```
注:上述代码中用到了uart.h文件,需要自行添加。
阅读全文