【STM32 IIC通信与温湿度传感器AHT20(I2C_AHT20)】

ops/2024/10/19 3:34:37/

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 最终效果展示
    • AHT20温湿度传感器(I2C_AHT20)
  • 1、工程配置
  • 2、代码
  • 如果您发现文章有错误请与我留言,感谢


最终效果展示

详细讲解视频

AHT20温湿度传感器(I2C_AHT20)

通过I²C读取AHT20温湿度计

板载AHT20传感器规格:

在这里插入图片描述
学习板上的AHT20传感器:

在这里插入图片描述

  • 编译并下载程序到学习板
  • 使用配套TYPE-C数据线,将学习板连接到计算机

在这里插入图片描述

  • 打开波特律动 串口助手 (keysking.com)在线串口调试助手,点击“选择串口”,选择USB Single Serial
  • 此时即可收到温湿度信息,如图所示

AHT20温湿度传感器(I2C_AHT20)


1、工程配置

  • 打开I²C外设:Pinout&Configuration -> Connectivity -> I2C1,将I2C模式选择为I2C

在这里插入图片描述

  • 打开串口2外设:Pinout&Configuration -> Connectivity -> USART2,将Mode选择为Asynchronous

在这里插入图片描述

  • 配置工程:在Project Manager -> Code Generator页面中,勾选Generate peripheral initialization as … per peripheral

在这里插入图片描述

2、代码

新建一个源文件和头文件

在这里插入图片描述

aht20.h

/** aht20.h**  Created on: Apr 25, 2024*      Author: lenovo*/#ifndef INC_AHT20_H_
#define INC_AHT20_H_#include "i2c.h"void AHT20_Init ();void AHT20_Read(float *Temperature , float *Humidity);
#endif /* INC_AHT20_H_ */

aht20.c

#include "aht20.h"#define AHT20_ADDRESS 0x70 // 从机地址
//AHT20 的驱动程序void AHT20_Init () //AHT20初始化函数  记住要在"aht20.h"中声明
{uint8_t readBuffer;//用于接收状态信息HAL_Delay(40);HAL_I2C_Master_Receive(&hi2c1, AHT20_ADDRESS, &readBuffer, 1, HAL_MAX_DELAY);//I2C读取函数,读数据函数 readBuffer此时获得了一个字节的状态字。if((readBuffer & 0x08) == 0x00) //判断第三位是否为0 发送0xBE命令初始化{uint8_t sendBuffer [3] = {0xBE , 0x08 , 0x00};HAL_I2C_Master_Transmit(&hi2c1, AHT20_ADDRESS, sendBuffer, 3, HAL_MAX_DELAY);//I2C发送函数}}void AHT20_Read(float *Temperature , float *Humidity) //AHT20读取温度湿度函数  记住要在"aht20.h"中声明
{uint8_t sendBuffer [3] = {0xAC , 0x33 , 0x00};uint8_t readBuffer [6];HAL_I2C_Master_Transmit(&hi2c1, AHT20_ADDRESS, sendBuffer, 3, HAL_MAX_DELAY);HAL_Delay(75);HAL_I2C_Master_Receive(&hi2c1, AHT20_ADDRESS, readBuffer, 6, HAL_MAX_DELAY);if((readBuffer[0] & 0x80) == 0x00){uint32_t date = 0;//接收温湿度需要2个半字节 所以要32date = ((uint32_t )readBuffer[3] >> 4) + ((uint32_t )readBuffer[2] << 4) + ((uint32_t )readBuffer[1] << 12);//对数据进行移位拼接.*Humidity = date * 100.0f / (1 << 20);//(1 << 20) 意为2的20次方. 乘100.0可以表示为百分数date = (((uint32_t )readBuffer[3] & 0x0F)<< 16) + ((uint32_t )readBuffer[4] << 8) + (uint32_t )readBuffer[5];//& 0x0F: 将这个无符号整数与十六进制数0x0F进行按位与操作。0x0F的二进制表示为00001111,这个操作会保留readBuffer[3]的低四位,即将高四位清零。*Temperature = date * 200.0f / (1 << 20) - 50;}
}

main.c

/* USER CODE BEGIN Header */
/********************************************************************************* @file           : main.c* @brief          : Main program body******************************************************************************* @attention** Copyright (c) 2024 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 "i2c.h"
#include "usart.h"
#include "gpio.h"/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "i2c.h"
#include <stdio.h>
#include "string.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 *//* 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();MX_I2C1_Init();MX_USART2_UART_Init();/* USER CODE BEGIN 2 */AHT20_Init ();//初始化AHT20float temperature , humidity ;char message [50];/* USER CODE END 2 *//* Infinite loop *//* USER CODE BEGIN WHILE */while (1){AHT20_Read( &temperature , &humidity); //读取AHT20sprintf(message ,"温度: %.lf ℃ , 湿度: %.lf %%\r\n",temperature , humidity);//拼接HAL_UART_Transmit(&huart2, (uint8_t*)message,strlen(message) , HAL_MAX_DELAY);//串口发�?�函�?HAL_Delay(1000);/* USER CODE END WHILE *//* 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_HSI;RCC_OscInitStruct.HSIState = RCC_HSI_ON;RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;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_HSI;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_0) != 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 */

如果您发现文章有错误请与我留言,感谢


http://www.ppmy.cn/ops/24374.html

相关文章

Linux如何redis清空缓存

通过命令清空缓存 登录redis redis-cli -h 127.0.0.1 -p 6379# 如果有密码需要下面这一步 auth 你的密码出现ok表示登录成功 查看所有key keys * 清空整个Redis服务器的数据 flushall

Vue+ElementUI实现文件照片音频视频预览

1. 需求是点击预览按钮 根据文件名的后缀去实现预览 2. 具体实现代码及逻辑 1.预览弹框 <el-dialog:visible.sync"visibleFile"width"40%":close-on-click-modal"false"close"cancelHandler":append-to-body"true">…

足球滚球数据分析靠谱吗?能不能通过大模型去实时预测?

足球滚球数据分析在一定程度上是靠谱的&#xff0c;但并非绝对可靠。滚球数据分析主要依赖于大量的历史数据、实时比赛数据以及相关的统计模型来预测比赛结果。这些数据可以包括球队的实力对比、球员状态、比赛进程、进球趋势、控球率变化等多个方面。 通过深入分析和挖掘这些数…

ES全文检索支持拼音和繁简检索

ES全文检索支持拼音和繁简检索 1. 实现目标2. 引入pinyin插件2.1 编译 elasticsearch-analysis-pinyin 插件2.2 安装拼音插件 3. 引入ik分词器插件3.1 已有作者编译后的包文件3.2 只有源代码的版本3.3 安装ik分词插件 4. 建立es索引5.测试检索6. 繁简转换 1. 实现目标 ES检索时…

Ansible-Tower安装破解

主机IP地址版本Ansible192.168.169.2042.9.1Tower192.168.169.2043.6.2 基础环境 systemctl disable firewalld --now && setenforce 0 sed -i s/SELINUXenforcing/SELINUXdisabled/g /etc/selinux/config mv /etc/yum.repos.d/CentOS-* /tmp/ curl -o /etc/yum.repo…

rpc和http的区别,使⽤场景

a. 区别&#xff1a; 传输协议 RPC:可以基于TCP协议&#xff0c;也可以基于HTTP协议 HTTP:基于HTTP协议 传输效率 RPC:使⽤⾃定义的TCP协议&#xff0c;可以让请求报⽂体积更⼩&#xff0c;或者使⽤HTTP2协议&#xff0c;也可以很好的减少报⽂的体积&#xff0c;提⾼传输效…

【Web】D^3CTF之浅聊d3pythonhttp——TE-CL请求走私

目录 step0 题目信息 step1 jwt空密钥伪造 step1.5 有关TE&CL的lab step2 TE-CL请求走私 payload1 payload2 step0 题目信息 注意到题目源码前端是flask写的&#xff0c;后端是web.py写的 frontend from flask import Flask, request, redirect, render_templat…

Chrome 插件如何开发?

开发 Chrome 插件涉及几个关键步骤&#xff0c;包括了解 Chrome 插件的架构、编写必要的代码、测试和发布。以下是开发 Chrome 插件的基本流程&#xff1a; 1. 了解 Chrome 插件的基础知识&#xff1a; - Chrome 插件通常由 HTML、CSS 和 JavaScript 文件组成。 - 它们可…