【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11

文章目录

    • 前言
    • 一、软件准备
    • 二、DHT11
      • 1.扩展板上模块的原理图以及我们需要配置的元素
      • 2.CubeMx的配置步骤
      • 3.代码修改以及应用
        • 方法1.以移植F103驱动包为方法
          • ①.在工程中添加大赛提供的G431的ds18b20驱动包和F103的DHT11的驱动包
          • ②.复制ds18b20的初始化部分到dht11的初始化部分,并修改GPIO的引脚。
          • ②.复制ds18b20的改变引脚为输入功能部分到dht11的改变引脚为输入功能部分,并修改GPIO的引脚。
          • ③.复制ds18b20的改变引脚为输出功能部分到dht11的改变引脚为输出功能部分,并修改GPIO的引脚。
          • ④.修改dht11.c中的dht11_read函数。
          • ⑤.修改dht11.c中的延时函数的宏定义。
          • ⑥.添加main.h到dht11.h
          • ⑦在main.c中编写测试代码
          • ⑧将ds18b20驱动从工程中移除(这一步可以不做)
        • 方法2.直接使用G431的DHT11例程驱动
          • ①.在工程中添加大赛提供的G431的DHT11例程中的dht11.c和dht11.h
          • ②.在dht11.c中添加u8的宏定义
          • ③.在dht11.c中的DHT11_Read_Data函数中修改并添加形参,以及形参赋值的语句
          • ④.在dht11.h中添加DHT11_Read_Data函数的新声明,同时将所有u8修改位unsigned char
          • ⑤在main.c中编写测试代码
        • 方法3.修改大赛提供的驱动包(此方法在2023.6.3更新)
          • ①.在工程中添加大赛提供的G431的dht11驱动包并修改名称为:dht11.c和dht11.h
          • ②.修改头文件如图所示。
          • ③.修改C文件中包含头文件名称为dht11.h。
          • ④.修改C文件中延时函数的i值(80Mhz修改为16,如果使用其他主频记得以比例替换)。
          • ⑤.修改C文件中的接收字节函数。
          • ⑥.在C文件中增加复位和检查函数。
          • ⑦.在C文件中增加读取温湿度函数。
          • ⑧.在main.c文件中增加头文件和变量声明。
          • ⑨.在main.c文件中增加测试代码。
    • 三、测试代码
      • 方法一
      • 方法二:
      • 方法三:
    • 四、演示效果
      • 方法一
      • 方法二
      • 方法三(偷了个懒方法二三其实现象差不多的)
    • 五、工程链接
    • 六、总结

前言

我们学完了DS18B20的应用之后,就开始学习DHT11的应用。
DHT11给我的感觉有点怪
第一就是使用时需要占用大量时间(测试了一下,一次读取花了20ms左右,相当于两次按键消抖所花的时间)

第二就是现在官方提供的驱动包只有F103版本的,对于G431只有DHT11的例程,没有专门的驱动包。

第三就是现在比赛中从来就没有考过DHT11的应用(不过为了保险起见还是要做准备)

本篇文章将会讲述如何应用F103的驱动包和G431大赛官方所给的例程来应用DHT11(比赛选一种方法就可以)。

一、软件准备

1、MDK4或者MDK5(可到官网或者其他途径获取,本人使用的是MDK5)
2、Cubemx(可到官网自行下载)
3、安装G4的包(1.2.0,1.3.0以及1.4.0均可)
4、串口调试助手(COM)

二、DHT11

1.扩展板上模块的原理图以及我们需要配置的元素

DHT11部分原理图:
【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第1张图片
模块在扩展板的布局:
【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第2张图片
分析:没什么好说的,知道HDQ连接的是PA7引脚就行。

2.CubeMx的配置步骤

RCC配置:略
设置调试接口:设置为Serial Wire
到此配置完成,不需要配置IO口。
生成工程:点击GENERATE CODE生成工程。

3.代码修改以及应用

方法1.以移植F103驱动包为方法

①.在工程中添加大赛提供的G431的ds18b20驱动包和F103的DHT11的驱动包

【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第3张图片
(我的ds18b20驱动包,是根据ds18b20篇的文章修改过的,其实不修改也没关系,反正后面都要移除掉的)

②.复制ds18b20的初始化部分到dht11的初始化部分,并修改GPIO的引脚。

【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第4张图片
【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第5张图片

②.复制ds18b20的改变引脚为输入功能部分到dht11的改变引脚为输入功能部分,并修改GPIO的引脚。

【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第6张图片
【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第7张图片

③.复制ds18b20的改变引脚为输出功能部分到dht11的改变引脚为输出功能部分,并修改GPIO的引脚。

【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第8张图片
【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第9张图片

④.修改dht11.c中的dht11_read函数。

【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第10张图片
【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第11张图片
画红框的部分都要修改为hal库的相应函数(原来的都是标准库函数)

⑤.修改dht11.c中的延时函数的宏定义。

【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第12张图片

⑥.添加main.h到dht11.h

【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第13张图片

⑦在main.c中编写测试代码

添加头文件:
【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第14张图片

参数定义:
【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第15张图片
液晶初始化:
【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第16张图片
读取部分:
【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第17张图片
这里的注释写错了,应该是不能小于108!!!

⑧将ds18b20驱动从工程中移除(这一步可以不做)

至此代码修改和编写已经完成可以下载到板子上进行测试了。

方法2.直接使用G431的DHT11例程驱动

由于目前为止,G431还没有给出专门的DHT11驱动,这里就假设例程中的驱动包是大赛给出的专门的驱动包来使用。

①.在工程中添加大赛提供的G431的DHT11例程中的dht11.c和dht11.h

【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第18张图片

②.在dht11.c中添加u8的宏定义

【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第19张图片

③.在dht11.c中的DHT11_Read_Data函数中修改并添加形参,以及形参赋值的语句

【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第20张图片

④.在dht11.h中添加DHT11_Read_Data函数的新声明,同时将所有u8修改位unsigned char

【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第21张图片

⑤在main.c中编写测试代码

添加头文件:
【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第22张图片
液晶初始化:
【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第23张图片
读取部分:
【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第24张图片
至此代码修改和编写已经完成可以下载到板子上进行测试了。

方法3.修改大赛提供的驱动包(此方法在2023.6.3更新)

①.在工程中添加大赛提供的G431的dht11驱动包并修改名称为:dht11.c和dht11.h

【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第25张图片

②.修改头文件如图所示。

【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第26张图片

③.修改C文件中包含头文件名称为dht11.h。

【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第27张图片

④.修改C文件中延时函数的i值(80Mhz修改为16,如果使用其他主频记得以比例替换)。

【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第28张图片

⑤.修改C文件中的接收字节函数。

【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第29张图片

⑥.在C文件中增加复位和检查函数。

【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第30张图片

⑦.在C文件中增加读取温湿度函数。

【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第31张图片

⑧.在main.c文件中增加头文件和变量声明。

【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第32张图片

【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第33张图片

⑨.在main.c文件中增加测试代码。

【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DHT11_第34张图片
至此代码修改和编写已经完成可以下载到板子上进行测试了。

三、测试代码

代码修改完成之后,添加lcd.h, lcd.c, fonts.h到工程中以方便显示。

方法一

dht11.h:

#ifndef __DHT11_H
#define __DHT11_H

#include "main.h"

void dht11_init (void );
void delay(unsigned int n);

unsigned int dht11_read(void);

#endif

dht11.c

#include "dht11.h"

#define delay_us(X)  delayd(X*120/5)

void delayd(unsigned int n)
{
  while (n--);
}

void dht11_init (void )
{
    GPIO_InitTypeDef	GPIO_InitStruct = {0};

    /* GPIO Ports Clock Enable */
    __HAL_RCC_GPIOA_CLK_ENABLE();


    GPIO_InitStruct.Pin = GPIO_PIN_7;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH ;
    GPIO_InitStruct.Pull = GPIO_PULLUP ;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

}

void mode_input(void )
{
    GPIO_InitTypeDef	GPIO_InitStruct = {0};

    /* GPIO Ports Clock Enable */

    GPIO_InitStruct.Pin = GPIO_PIN_7;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}
void mode_output(void )
{
    GPIO_InitTypeDef	GPIO_InitStruct = {0};

    GPIO_InitStruct.Pin = GPIO_PIN_7;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    GPIO_InitStruct.Pull = GPIO_NOPULL ;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}

unsigned int dht11_read(void)
{
  int i;
  long long val;
  int timeout;

	HAL_GPIO_WritePin(GPIOA, GPIO_PIN_7, GPIO_PIN_RESET);
  delay_us(18000);  //pulldown  for 18ms
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_7, GPIO_PIN_SET);
  delay_us( 20 );	//pullup for 30us

  mode_input();

  //等待DHT11拉高,80us
  timeout = 5000;
  while( (! HAL_GPIO_ReadPin  (GPIOA, GPIO_PIN_7)) && (timeout > 0) ) timeout--;	 //wait HIGH

  //等待DHT11拉低,80us
  timeout = 5000;
  while( HAL_GPIO_ReadPin (GPIOA, GPIO_PIN_7) && (timeout > 0) ) timeout-- ;	 //wait LOW

#define CHECK_TIME 28

  for(i=0;i<40;i++)
  {
	timeout = 5000;
	while( (! HAL_GPIO_ReadPin  (GPIOA, GPIO_PIN_7)) && (timeout > 0) ) timeout--;	 //wait HIGH

	delay_us(CHECK_TIME);
	if ( HAL_GPIO_ReadPin (GPIOA, GPIO_PIN_7) )
	{
	  val=(val<<1)+1;
	} else {
	  val<<=1;
	}

	timeout = 5000;
	while( HAL_GPIO_ReadPin (GPIOA, GPIO_PIN_7) && (timeout > 0) ) timeout-- ;	 //wait LOW
  }

  mode_output();
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_7, GPIO_PIN_SET);

  if (((val>>32)+(val>>24)+(val>>16)+(val>>8) -val ) & 0xff  ) return 0;
    else return val>>8; 

}

main.h:没有修改故不放出
main.c:

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2023 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "dht11.h"
#include "lcd.h"
#include "stdio.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
unsigned int DHT11_Value; //read函数接收参数
unsigned int DHT11Tick; //控制每隔一段时间读取的Tick
unsigned char tempi; //温度整数部分
unsigned char tempf; //温度小数部分
unsigned char humii; //湿度整数部分
unsigned char humif; //湿度小数部分
float temp; //温度;
float humi; //湿度
char text[30];
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
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();
  /* USER CODE BEGIN 2 */
	LCD_Init();
	LCD_Clear(Black);
	LCD_SetBackColor(Black);
	LCD_SetTextColor(White);
	DHT11_Value = dht11_read(); //提前读取防止刚上电一瞬间出现0。
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
		if(uwTick - DHT11Tick > 120) //每隔120ms读取一次(不能小于108)
		{
			DHT11Tick = uwTick;
			DHT11_Value = dht11_read();
			tempi = DHT11_Value >> 8 & 0xff;
			tempf = DHT11_Value >> 0 & 0xff;
			humii = DHT11_Value >> 24 & 0xff;
			humif = DHT11_Value >> 16 & 0xff;
			temp = tempi + tempf / 10.0;
			humi = humii + humif / 10.0;
		}
		sprintf(text, "Temp:%.1f", temp);
		LCD_DisplayStringLine(Line0, text);
		sprintf(text, "Humi:%.1f", humi);
		LCD_DisplayStringLine(Line1, text);	
  }
  /* USER CODE END 3 */
}

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

  /** Configure the main internal regulator output voltage
  */
  HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** 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.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV3;
  RCC_OscInitStruct.PLL.PLLN = 20;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  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_DIV1;
  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 */

方法二:

dht11.h:

#ifndef __DHT11_H
#define __DHT11_H

#include "main.h"

#define	DHT11_PIN_PORT       GPIOA
#define	DHT11_PIN        GPIO_PIN_7
#define	DHT11_PIN_CLOCK  __HAL_RCC_GPIOA_CLK_ENABLE()
#define	DHT11_PIN_OUT_H   HAL_GPIO_WritePin(DHT11_PIN_PORT, DHT11_PIN, GPIO_PIN_SET)
#define	DHT11_PIN_OUT_L   HAL_GPIO_WritePin(DHT11_PIN_PORT, DHT11_PIN, GPIO_PIN_RESET)
#define	DHT11_PIN_IN      HAL_GPIO_ReadPin(DHT11_PIN_PORT, DHT11_PIN)


unsigned char DHT11_Init(void);//初始化DHT11
unsigned char DHT11_Read_Data(unsigned char *tempi, unsigned char *tempf, unsigned char *humii, unsigned char *humif); //读取温湿度
unsigned char DHT11_Read_Byte(void);//读出一个字节
unsigned char DHT11_Read_Bit(void);//读出一个位
unsigned char DHT11_Check(void);//检测是否存在DHT11
void DHT11_Rst(void);//复位DHT11
#endif

dht11.c

#include "dht11.h"

#define u8 unsigned char


#define Delay_us(X)  delay((X)*80/5)

void delay(unsigned int n)
{
    while(n--);
}



void DHT11_PIN_OUT(void)
{
    GPIO_InitTypeDef GPIO_InitStruct = {0};

    /**/
    GPIO_InitStruct.Pin = DHT11_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(DHT11_PIN_PORT, &GPIO_InitStruct);
}
void DHT11_PIN_INPUT(void)
{
    GPIO_InitTypeDef GPIO_InitStruct = {0};
    DHT11_PIN_CLOCK;
    /**/
    GPIO_InitStruct.Pin = DHT11_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    HAL_GPIO_Init(DHT11_PIN_PORT, &GPIO_InitStruct);
}
//复位DHT11
void DHT11_Rst(void)
{
    DHT11_PIN_OUT(); 	//设置为输出
    DHT11_PIN_OUT_L; 	//低电平
    HAL_Delay(20);	//拉低至少18ms
    DHT11_PIN_OUT_H; 	//高电平
    Delay_us(60);     	//主机拉高20~40us
}

//等待DHT11的回应
//返回1:未检测到DHT11的存在
//返回0:存在
u8 DHT11_Check(void)
{
    u8 re = 0;
    DHT11_PIN_INPUT();      //设置为输出
    while (DHT11_PIN_IN && re < 100) //DHT11会拉低40~80us
    {
        re++;
        Delay_us(1);
    };
    if(re >= 100)return 1;
    else re = 0;
    while (!DHT11_PIN_IN && re < 100) //DHT11拉低后会再次拉高40~80us
    {
        re++;
        Delay_us(1);
    };
    if(re >= 100)return 1;
    return 0;
}

//DHT11读取一个位
u8 DHT11_Read_Bit(void)
{
    u8 re = 0;
    while(DHT11_PIN_IN && re < 110) //等待变为低电平
    {
        re++;
        Delay_us(1);
    }
    re = 0;
    while(!DHT11_PIN_IN && re < 110) //等待变为高电平
    {
        re++;
        Delay_us(1);
    }
    Delay_us(80);//等待40us
    if(DHT11_PIN_IN)return 1;
    else return 0;
}

//从DHT11读取一个字节
u8 DHT11_Read_Byte(void)
{
    u8 i, dat;
    dat = 0;
    for (i = 0; i < 8; i++)
    {
        dat <<= 1;
        dat |= DHT11_Read_Bit();
    }
    return dat;
}

//从DHT11读取一次数据
u8 DHT11_Read_Data(u8 *tempi, u8 *tempf, u8 *humii, u8 *humif)
{
    u8 buf[5];
    u8 i;
    DHT11_Rst();
    if(DHT11_Check() == 0)
    {
        for(i = 0; i < 5; i++)
        {
            buf[i] = DHT11_Read_Byte();
        }
        if((buf[0] + buf[1] + buf[2] + buf[3]) == buf[4])
        {
            *humii = buf[0];
						*humif = buf[1];
            *tempi = buf[2];
						*tempf = buf[3];
        }
    }
    else return 1;
    return 0;
}

//初始化DHT11的IO口,同时检测DHT11的存在

u8 DHT11_Init(void)
{
    GPIO_InitTypeDef GPIO_InitStruct = {0};
    DHT11_PIN_CLOCK;;
    GPIO_InitStruct.Pin = DHT11_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(DHT11_PIN_PORT, &GPIO_InitStruct);

    DHT11_Rst();
    return DHT11_Check();
}

main.h:没有修改故不放出
main.c:

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2023 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "lcd.h"
#include "dht11.h"
#include "stdio.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
unsigned char tempi;
unsigned char humii;
unsigned char tempf;
unsigned char humif;
float temp;
float humi;
char text[30];
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
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();
  /* USER CODE BEGIN 2 */
	LCD_Init();
	LCD_Clear(Black);
	LCD_SetBackColor(Black);
	LCD_SetTextColor(White);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
		DHT11_Read_Data(&tempi, &tempf, &humii, &humif); //可以不用每隔一段时间采集一次,
														 //但是不能放入中断执行
		temp = tempi + tempf / 10.0;
		humi = humii + humif / 10.0;
		sprintf(text, "temp:%.2fhumi:%.2f", temp, humi);
		LCD_DisplayStringLine(Line0, text);
  }
  /* USER CODE END 3 */
}

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

  /** Configure the main internal regulator output voltage
  */
  HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** 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.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV3;
  RCC_OscInitStruct.PLL.PLLN = 20;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  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_DIV1;
  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 */

方法三:

dht11.h:

#ifndef __DHT11_H
#define __DHT11_H

#include "main.h"

#define HDQ		GPIO_PIN_7

typedef struct {
	uint8_t humidity_high;
	uint8_t humidity_low;
	uint8_t temperature_high;
	uint8_t temperature_low;
}dht11Data;

void dht11Init(void);
void dht11Read(void);


#endif

dht11.c:

#include "dht11.h"


dht11Data dht11;

//
static void usDelay(uint32_t us)
{
	uint16_t i = 0;
	while(us--){
		i = 16; /******************************/
		while(i--);
	}
}

//
void outDQ(uint8_t i)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	
	
	GPIO_InitStructure.Pin = HDQ;
	GPIO_InitStructure.Speed = GPIO_SPEED_FREQ_HIGH;
	GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP;
	HAL_GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	if(!i) 
		HAL_GPIO_WritePin(GPIOA, HDQ, GPIO_PIN_RESET);
	else 
		HAL_GPIO_WritePin(GPIOA, HDQ, GPIO_PIN_SET);
}

//
void inDQ(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	
	GPIO_InitStructure.Pin = HDQ;
	GPIO_InitStructure.Mode = GPIO_MODE_INPUT;
	GPIO_InitStructure.Pull = GPIO_NOPULL;
	HAL_GPIO_Init(GPIOA, &GPIO_InitStructure);
}

//
void dht11Init(void)
{
    __HAL_RCC_GPIOA_CLK_ENABLE();
	outDQ(1);			
}

//
uint8_t recData(void)
{
	uint8_t i,temp=0,j=220;
	
	for(i=0; i<8; i++){
		while(HAL_GPIO_ReadPin(GPIOA,HDQ)); /*****************/
		while(!HAL_GPIO_ReadPin(GPIOA,HDQ));
		usDelay(40);
		if(HAL_GPIO_ReadPin(GPIOA,HDQ))
		{
			temp=(temp<<1)|1;
			while(HAL_GPIO_ReadPin(GPIOA,HDQ)&&(j--));	
		}	
		else
		{
			temp=(temp<<1)|0;
		}
	}
	return temp;
}

void dht11_rst(void)
{
	outDQ(0);
	HAL_Delay(20); //拉低至少18ms
	outDQ(1); 
	usDelay(60); //主机拉高20-40us
}

unsigned char dht11_check(void)
{
	unsigned char re = 0;
	inDQ(); //设置为输入
	while(HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_7) && re < 100) //DHT11会拉低40-80us
	{
		re++;
		usDelay(1);
	}
	if(re >= 100) return 1;
	else re = 0;
	while(!HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_7) && re < 100) //DHT11拉低后会再拉高40-80us
	{
		re++;
		usDelay(1);
	}
	if(re >= 100) return 1;
	else return 0;
}

void dht11Read(void)
{
	unsigned char buf[5];
	dht11_rst();
	if(dht11_check() == 0)
	{
		for(unsigned char i = 0; i < 5; i++)
		{
			buf[i] = recData();
		}
		if(buf[0] + buf[1] + buf[2] + buf[3] == buf[4])
		{
			dht11.humidity_high = buf[0];
			dht11.humidity_low = buf[1];
			dht11.temperature_high = buf[2];
			dht11.temperature_low = buf[3];
		}
	}
}

main.h:没有修改故不放出
main.c:

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2023 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "dht11.h"
#include "lcd.h"
#include "stdio.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
char text[30];
extern dht11Data dht11;
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
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();
  /* USER CODE BEGIN 2 */
	LCD_Init();
	LCD_Clear(Black);
	LCD_SetBackColor(Black);
	LCD_SetTextColor(White);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
		dht11Read();
		sprintf(text, "humi:%.2f", dht11.humidity_high + dht11.humidity_low / 10.0);
		LCD_DisplayStringLine(Line0, text);
		sprintf(text, "temp:%.2f", dht11.temperature_high + dht11.temperature_low / 10.0);
		LCD_DisplayStringLine(Line1, text);
  }
  /* USER CODE END 3 */
}

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

  /** Configure the main internal regulator output voltage
  */
  HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** 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.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV3;
  RCC_OscInitStruct.PLL.PLLN = 20;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  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_DIV1;
  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 */

四、演示效果

方法一

方法二

方法三(偷了个懒方法二三其实现象差不多的)

五、工程链接

DHT11模块方法1工程
DHT11模块方法2工程
DHT11模块方法3工程

六、总结

以上就是DHT11的配置过程,测试代码以及测试效果
以往的扩展板模块:
【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→SEG
【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→双路ADC/AO1, AO2
【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→光敏电阻/TRAO, TRAO
【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→AKEY
【STM32G431RBTx】备战蓝桥杯嵌入式→扩展模块→DS18B20

你可能感兴趣的:(stm32,单片机,蓝桥杯)