STM32F103C6T6使用HAL库驱动DHT11
DHT11数据格式以及传输方式
? DHT11采用单条数据线一次通讯时间在4ms左右。数据分小数部分和整数部分,每次传输40bit数据格式为:
8bit湿度整数数据 | 8bit湿度小数数据 | 8bi温度整数数据 | 8bit温度小数数据 | 8bit校验和 |
---|
其中湿度小数读取为零,即湿度精确度为1%,温度小数部分为0-9,精确度为0.1°C。
DHT11通讯时序
驱动代码
头文件
#ifndef __DHT11_H__
#define __DHT11_H__
#include "main.h"
#define DQ_PIN GPIO_PIN_0
#define DQ_PORT GPIOA
#define ONELINE_IN HAL_GPIO_ReadPin(DQ_PORT,DQ_PIN)
#define ONELINE_OUT(PIN) HAL_GPIO_WritePin(DQ_PORT,DQ_PIN, PIN)
typedef uint8_t u8;
typedef struct{
float h;
float t;
} DHT11_INFO;
extern DHT11_INFO dht11;
void DHT11_Init();
void DHT11_Read();
u8 Oneline_Start();
#endif
驱动文件
#include "DHT11.h"
u8 crc;
DHT11_INFO dht11;
u8 error = 0;
#define MY_ONELINE
void gpio_out(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
GPIO_InitStruct.Pin = DQ_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_OD;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(DQ_PORT, &GPIO_InitStruct);
}
void gpio_in(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
GPIO_InitStruct.Pin = DQ_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(DQ_PORT, &GPIO_InitStruct);
}
u8 Oneline_Start(){
error = 0;
gpio_out();
ONELINE_OUT(0);
HAL_Delay(20);
ONELINE_OUT(1);
delay_us(50);
gpio_in();
if(!ONELINE_IN){
while(!ONELINE_IN);
while(ONELINE_IN);
return 1;
}
else return 0;
}
u8 Oneline_bit(){
u8 flag; u8 retry = 0;
while(!ONELINE_IN && retry++ < 100) delay_us(1);
if(retry >= 100) return 2;
delay_us(30);
flag = ONELINE_IN;
retry = 0;
while(ONELINE_IN && retry++ < 100) delay_us(1);
return flag;
}
u8 Oneline_Read(){
u8 i, bit, byte=0;
if(error) return 0;
for(i=0;i<8;i++){
bit = Oneline_bit();
if(bit > 1) {
error = 1;
return 0;
}
byte <<= 1; byte |= bit;
}
return byte;
}
void DHT11_Read(){
u8 tem, tem_deci, humid, humid_deci, crc ,crc_res;
if(Oneline_Start()){
humid = Oneline_Read();
humid_deci = Oneline_Read();
tem = Oneline_Read();
tem_deci = Oneline_Read();
crc = Oneline_Read();
crc_res = crc == (humid+humid_deci+tem+tem_deci);
if(!error && crc_res) {
dht11.t = tem + tem_deci/10.0f;
dht11.h = humid;
}
}
}
void DHT11_Init(){
HAL_Delay(500);
}
us级延时
使用了一个空闲的定时器设置计数单位为1us并通过轮询进行延时
void delay_us(uint32_t us){
__HAL_TIM_SetCounter(&htim3, 0);
__HAL_TIM_ENABLE(&htim3);
while(__HAL_TIM_GetCounter(&htim3) < us);
__HAL_TIM_DISABLE(&htim3);
}
|