#include "tmp117.h" #include "i2c.h" // 初始化温度传感器 HAL_StatusTypeDef TMP117_Init(void) { // 配置值: uint8_t config_data[2] = {0x0C, 0x00}; // 高字节在前,单次转换,1100 0000 0000,12.5ms return HAL_I2C_Mem_Write(&hi2c1, TMP117_ADDR << 1, TMP117_CONFIG_REG, I2C_MEMADD_SIZE_8BIT, config_data, 2, 100); } // 从寄存器读取双字节数据 HAL_StatusTypeDef TMP117_Read(uint8_t reg, uint8_t *buffer) { return HAL_I2C_Mem_Read(&hi2c1, TMP117_ADDR << 1, reg, I2C_MEMADD_SIZE_8BIT, buffer, 2, 100); } // 获取温度值(单位:℃) HAL_StatusTypeDef TMP117_Get_Temp(float *temp) { uint8_t raw_data[2] = {0}; int16_t temp_raw; if (HAL_OK == TMP117_Read(TMP117_TEMP_REG, raw_data)) { temp_raw = (raw_data[0] << 8) | raw_data[1]; *temp = temp_raw * 0.0078125f; } else { *temp = 0; return HAL_ERROR; } if(*temp <= -60) { *temp = -60; } if(*temp >= 150) { *temp = 150; } return HAL_OK; }