第十二章:温度传感器拓展模块

发布于:2025-06-27 ⋅ 阅读:(16) ⋅ 点赞:(0)

1.资源介绍

Tem

MCU

SCL

PA12

SDA

PA11

2.STM32CuBeMX配置

3.程序编写

#include "main.h"
#include "i2c.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#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 */

/* 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 */
int fputc(int ch,FILE *p)
{
	HAL_UART_Transmit(&huart2,(uint8_t *)&ch,1,0xffff);
	return ch;
}
float STS30_Proc(void)                                                                              //温度计程序
{
    uint8_t tem_data[2];//写入数据缓冲区 
    float tem;                                                        

    tem_data[0] = 0x24;
    tem_data[1] = 0x0B;
    
    HAL_I2C_Master_Transmit(&hi2c2, 0x4A<<1, tem_data, 2, 10);//开启温度转化 为下一次运行准备数据
    HAL_Delay(100);
    HAL_I2C_Master_Receive(&hi2c2, (0x4A << 1)+1, tem_data, 2, 10);//初始化时开启了一次温度转化 现在来读取 或者之前运行过的温度转化 现在读取
            
    tem = (float)((tem_data[0] << 8 | tem_data[1]) * 175.0 / 65535 - 45); //计算并返回温度结果
    return tem;
}
/* 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 */
  MX_USART2_UART_Init();
  /* USER CODE END SysInit */
  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_I2C2_Init();
  
  /* USER CODE BEGIN 2 */
  printf("this is tem init\r\n");
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
	 STS30_Proc();
	 printf("tem:%.2f\r\n",STS30_Proc());
	 HAL_Delay(500);
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}


网站公告

今日签到

点亮在社区的每一天
去签到