Bootstrap

stm32(HAL)版下的DHT11外设

DHT11温湿度传感器

DHT11数据进行传输的格式是怎样的?

DHT11数据进行传输的原理是怎样的?

​ DHT算是一种典型的温湿度传感模块,既能传递温度又能进行湿度的测量,DHT的接线方法通常如下:

2.数据传输的方法&通讯过程:

​ DHT11的数据传输方向为单向的,外设 ==> MCU,通过数据引脚串行方式一次性完整的数据传输为40bit(40位,5字节),高位先输出,其中 8bit湿度整数数据+8bit湿度小数数据+8bit温度整数数据+8bit温度小数数据。最后再输出所有数据的总和

通讯过程:

​ 首先主机总线[^22]空闲状态时,VCC呈现高电平,然后主机端将其拉低并持续18ms以上,以进行DHT11起始信号的检测。然后DHT11发出起始信号并拉高电平进行等待。此时开始信号完成,需将DATA对应的IO口切换为输入模式,随后总线为由DHT11发出的80us低电平的响应信号,然后DHT在此吧总线拉高80us准备发送数据,数据以1bit位的方式进行传输,不同的数据传输高电平的延时不一致

下图较为重要,程序常用到

​ 传输开始后,数据0的表示方法:

​ 传输开始后,数据1的表示方法:

​ 在最后一位传输结束后,总线先由DHT11拉低50us,随后由相关上拉电阻拉高后进入空闲状态(参考第一张图)。此外需要注意的是图中的总线由两种颜色进行标注,当线色为黑色时,此时由主机端MCU控制总线的高低电平,进行一系列数据读取的“预处理”操作,而线色变为灰色时则该总线控制权交由到外设DHT上,主机端只管根据电平占位时间,判断进行数据的接受即可。而我们编程能操作的也只有主机端(MCU)。

3. 代码实现

​ 需要注意的是温湿度传感器可直接进行温湿度感知传感,并不需要进行ADC转换。

引脚配置与驱动相关

​ 需要注意的是DHT11对时序比较敏感,时序配置不当会导致数据出现逻辑错误

#include "DHT11.h"
#include "tim.h"

/*配置为普通推挽模式输出,用于拉高电平*/
void DHT11_PP_OUT(void)
{
    GPIO_InitTypeDef    GPIO_InitStructure;
    //GPIO_InitStructure.Mode =   GPIO_MODE_AF_PP;
    GPIO_InitStructure.Mode   = GPIO_MODE_OUTPUT_PP; 
    GPIO_InitStructure.Pin  =   DHT11_PIN;
    GPIO_InitStructure.Speed    =   GPIO_SPEED_FREQ_HIGH;
    GPIO_InitStructure.Pull     =   GPIO_NOPULL;
    HAL_GPIO_Init(DHT11_PORT, &GPIO_InitStructure);
}

/*配置为输入模式,用于接收数据相关*/
void DHT11_UP_IN(void)
{
    GPIO_InitTypeDef    GPIO_InitStructure;
    GPIO_InitStructure.Mode  =   GPIO_MODE_INPUT;
    GPIO_InitStructure.Pin   =  DHT11_PIN;
    GPIO_InitStructure.Pull  = GPIO_PULLUP;
    GPIO_InitStructure.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(DHT11_PORT, &GPIO_InitStructure);
}

/*
@brief: 读取一个字节
*/
uint8_t DHT11_ReadByte()
{
    uint8_t resData = 0;
    //先高位再低位进行传输
    for (int i = 0; i < 8; i++)
    {
        /* 等待低电平结束 */
        while(DHT11_ReadPin == 0);
        //高电平延时40us  因为数据为0时持续26-28us,超过为1
        my_delay_us(40);
        //数据为1
        if (DHT11_ReadPin == 1)
        {
            /* code */
            //等待高电平结束
             while(DHT11_ReadPin == 1);
             resData |= (uint8_t)(0x01 << (7 - i));
        }
        //数据为0
        else
        { 
             resData &= ~(uint8_t)(0x01 << (7 - i));
        }
        
    }
    
    return resData;
}

/*
@brief: 读取温湿度
*/
uint8_t DHT11_ReadData(DHT11_Data_Typedef *DHT11_Data)
{
    //printf("开始读取数据!");
    //1.主机输出拉低电平
    DHT11_PP_OUT();
    DHT11_PULL_LOW;
    //持续18ms以上
    //my_delay_us(20);
    my_delay_ms(20);
    //2.主机拉高,持续20-40us
    DHT11_PULL_HIGH;
    my_delay_us(30);

    //3.从机对总线进行接入,主机获取电平数据处理
    DHT11_UP_IN();
    //收到从机的响应信号
    if (DHT11_ReadPin == 0)
    {	
        /*等待低,高电平应答信号结束*/
        while(DHT11_ReadPin == 0);
        while(DHT11_ReadPin == 1);

        //4.正式接受数据处理
        DHT11_Data -> humi_int = DHT11_ReadByte();
        DHT11_Data->humi_dec = DHT11_ReadByte();
        DHT11_Data->temp_int = DHT11_ReadByte();
        DHT11_Data->temp_dec = DHT11_ReadByte();
        DHT11_Data->chek_sum = DHT11_ReadByte();

        //5.读取结束,主机拉高
        DHT11_PP_OUT();
        DHT11_PULL_HIGH;

         printf("Check: %d\r\n",DHT11_Data->chek_sum);
        //6.数据校验并进行回传
        if (DHT11_Data->chek_sum == DHT11_Data -> humi_int + DHT11_Data->humi_dec + DHT11_Data->temp_int + DHT11_Data->temp_dec)
        {
            return 1;
        }
        
    }
    return 0;
    
}

时钟定时器相关

#include "tim.h"

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

TIM_HandleTypeDef htim2;

/* TIM2 init function */
void MX_TIM2_Init(void)
{

  /* USER CODE BEGIN TIM2_Init 0 */

  /* USER CODE END TIM2_Init 0 */

  TIM_SlaveConfigTypeDef sSlaveConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};

  /* USER CODE BEGIN TIM2_Init 1 */

  /* USER CODE END TIM2_Init 1 */
  htim2.Instance = TIM2;
  htim2.Init.Prescaler = 71;
  htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim2.Init.Period = 65535;
  htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
  if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
  {
    Error_Handler();
  }
  sSlaveConfig.SlaveMode = TIM_SLAVEMODE_DISABLE;
  sSlaveConfig.InputTrigger = TIM_TS_ITR0;
  if (HAL_TIM_SlaveConfigSynchro(&htim2, &sSlaveConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }

}

void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* tim_baseHandle)
{

  if(tim_baseHandle->Instance==TIM2)
  {
  /* USER CODE BEGIN TIM2_MspInit 0 */

  /* USER CODE END TIM2_MspInit 0 */
    /* TIM2 clock enable */
    __HAL_RCC_TIM2_CLK_ENABLE();
  /* USER CODE BEGIN TIM2_MspInit 1 */

  /* USER CODE END TIM2_MspInit 1 */
  }
}

void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef* tim_baseHandle)
{

  if(tim_baseHandle->Instance==TIM2)
  {
  /* USER CODE BEGIN TIM2_MspDeInit 0 */

  /* USER CODE END TIM2_MspDeInit 0 */
    /* Peripheral clock disable */
    __HAL_RCC_TIM2_CLK_DISABLE();
  /* USER CODE BEGIN TIM2_MspDeInit 1 */

  /* USER CODE END TIM2_MspDeInit 1 */
  }
}

/* USER CODE BEGIN 1 */
void my_delay_us(uint16_t   us)
{
  __HAL_TIM_SET_COUNTER(&htim2, 0);
  HAL_TIM_Base_Start(&htim2);

  while(__HAL_TIM_GET_COUNTER(&htim2) < us);

  HAL_TIM_Base_Stop(&htim2);
}

void my_delay_ms(uint16_t ms)
{
  
  //my_delay_us(ms * 1000);
  //while(ms * my_delay_us(1000));
  for (int i = 0; i < ms; i++)
  {
    /* code */
    my_delay_us(1000);
  }
  
}

/* USER CODE END 1 */

main函数

#include "main.h"
#include "i2c.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"
#include "OLED.h"
#include "DHT11.h"


DHT11_Data_Typedef DHT11_Data;

void SystemClock_Config(void);

int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_TIM2_Init();
  MX_USART1_UART_Init();
  OLED_Init();
  /* USER CODE BEGIN 2 */

	//printf("success2!");
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */
    my_delay_ms(1000);
    if (DHT11_ReadData(&DHT11_Data))
    {
      //温度显示
      OLED_ShowString(1,1, "Temp:");
      OLED_ShowNum(1,6, DHT11_Data.temp_int, 2);
      OLED_ShowChar(1,8 ,'.');
      OLED_ShowNum(1,9, DHT11_Data.temp_dec, 2);
      //湿度显示
      OLED_ShowString(2,1, "Humi:");
      OLED_ShowNum(2,6, DHT11_Data.humi_int, 2);
      OLED_ShowChar(2,8 ,'.');
      OLED_ShowNum(2,9, DHT11_Data.humi_dec, 2);
    }
    else
    {
      //OLED_ShowString(1,1, "ERROR!");
			printf("ERROR");
    }
    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */


;