#include "tmp117.h" #include "i2c.h" #include "cmsis_os.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); } static float calculateAverage(float arr[], int avgLength) { float sum = 0; // 遍历数组(最多10个元素),收集非零值直到达到指定数量 for (int i = 0; i < 10; ++i) { sum += arr[i]; } // 计算平均值并限制最大值 float average = sum / avgLength; return average; } // 获取温度值(单位:℃) #define COLLECT_DATA_NUM 10 HAL_StatusTypeDef TMP117_Get_Temp(float *temp) { uint8_t raw_data[2] = {0}; int16_t temp_raw; uint8_t ret_falt = 0; float ret_temp; float temp_temp[COLLECT_DATA_NUM] = {0}; for(int i = 0; i= COLLECT_DATA_NUM) { *temp = 0; return HAL_ERROR; } ret_temp = calculateAverage(temp_temp, COLLECT_DATA_NUM - ret_falt); if(ret_temp <= -60) { *temp = -60; }else if(ret_temp >= 150) { *temp = 150; }else { *temp = ret_temp; } return HAL_OK; }