2025-09-18 2:08 AM - last edited on 2025-09-18 3:25 AM by Amel NASRI
Hello,
I am working on the STM32G431RB Nucleo board, specifically on the internal temperature sensor. I am facing issues in getting accurate readings.
For your reference, I have attached:
My code implementation
An Excel sheet comparing temperature readings with respect to a thermal chamber
The sensor readings are not matching the expected values. Could you please guide me on the correct way to use this sensor and help identify any corrections required in my implementation?
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
uint16_t adc_val,ref_adc,ts_ref,ts_cal1,ts_cal2;
float vdd,temp,vdd,avg_temp;
float alpha =0.075;
#define TS_CAL1 ((uint16_t * ) 0x1FFF75A8)
#define TS_CAL2 ((uint16_t * ) 0x1FFF75Ca)
#define ref_val ((uint16_t * ) 0x1FFF75aa)
/* 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 ---------------------------------------------------------*/
ADC_HandleTypeDef hadc1;
DMA_HandleTypeDef hdma_adc1;
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
static void MX_ADC1_Init(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_DMA_Init();
MX_ADC1_Init();
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
HAL_ADC_Start(&hadc1);
HAL_ADC_PollForConversion(&hadc1, 10);
adc_val=HAL_ADC_GetValue(&hadc1);
HAL_ADC_PollForConversion(&hadc1, 10);
ref_adc=HAL_ADC_GetValue(&hadc1);
HAL_ADC_Stop(&hadc1);
//-------------------vdd calculation
ts_ref=*ref_val;
ts_cal1=*TS_CAL1;
ts_cal2=*TS_CAL2;
vdd=((float)(ts_ref*3.0f)/(float)ref_adc);
temp = ((float)(adc_val*(vdd/3.0f)-ts_cal1))*(110.0f-30.0f)/((float)(ts_cal2-ts_cal1))+30.0f;
avg_temp=alpha*temp+(1.0f-alpha)*avg_temp;
}
/* 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_BOOST);
/** 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_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV4;
RCC_OscInitStruct.PLL.PLLN = 85;
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_4) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief ADC1 Initialization Function
* None
* @retval None
*/
static void MX_ADC1_Init(void)
{
/* USER CODE BEGIN ADC1_Init 0 */
/* USER CODE END ADC1_Init 0 */
ADC_MultiModeTypeDef multimode = {0};
ADC_ChannelConfTypeDef sConfig = {0};
/* USER CODE BEGIN ADC1_Init 1 */
/* USER CODE END ADC1_Init 1 */
/** Common config
*/
hadc1.Instance = ADC1;
hadc1.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4;
hadc1.Init.Resolution = ADC_RESOLUTION_12B;
hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc1.Init.GainCompensation = 0;
hadc1.Init.ScanConvMode = ADC_SCAN_ENABLE;
hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
hadc1.Init.LowPowerAutoWait = DISABLE;
hadc1.Init.ContinuousConvMode = ENABLE;
hadc1.Init.NbrOfConversion = 2;
hadc1.Init.DiscontinuousConvMode = DISABLE;
hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
hadc1.Init.DMAContinuousRequests = ENABLE;
hadc1.Init.Overrun = ADC_OVR_DATA_PRESERVED;
hadc1.Init.OversamplingMode = DISABLE;
if (HAL_ADC_Init(&hadc1) != HAL_OK)
{
Error_Handler();
}
/** Configure the ADC multi-mode
*/
multimode.Mode = ADC_MODE_INDEPENDENT;
if (HAL_ADCEx_MultiModeConfigChannel(&hadc1, &multimode) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_TEMPSENSOR_ADC1;
sConfig.Rank = ADC_REGULAR_RANK_1;
sConfig.SamplingTime = ADC_SAMPLETIME_640CYCLES_5;
sConfig.SingleDiff = ADC_SINGLE_ENDED;
sConfig.OffsetNumber = ADC_OFFSET_NONE;
sConfig.Offset = 0;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_VREFINT;
sConfig.Rank = ADC_REGULAR_RANK_2;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN ADC1_Init 2 */
/* USER CODE END ADC1_Init 2 */
}
/**
* Enable DMA controller clock
*/
static void MX_DMA_Init(void)
{
/* DMA controller clock enable */
__HAL_RCC_DMAMUX1_CLK_ENABLE();
__HAL_RCC_DMA1_CLK_ENABLE();
/* DMA interrupt init */
/* DMA1_Channel1_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);
}
/**
* @brief GPIO Initialization Function
* None
* @retval None
*/
static void MX_GPIO_Init(void)
{
/* USER CODE BEGIN MX_GPIO_Init_1 */
/* USER CODE END MX_GPIO_Init_1 */
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
/* USER CODE BEGIN MX_GPIO_Init_2 */
/* USER CODE END MX_GPIO_Init_2 */
}
/* 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.
* file: pointer to the source file name
* 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 */
Solved! Go to Solution.
2025-09-19 8:09 AM
I wouldn't expect chamber temperature and internal temperature to match exactly. The chamber is ambient and the internal temp is the junction temperature. The board will take a while to come to steady state and the internal temperature will also be higher (at steady state) than ambient.
If you fix the 130 vs 110 error as @RobK1 notes, see if values are more consistent with expectations. Junction should be a little higher than ambient. Amount depends on how much energy it's using.
In my experience, typical accuracy is within a few degrees C.
2025-09-19 10:21 PM - edited 2025-09-19 10:37 PM
1. check this value in stm32g4xx_ll_adc. or corresponding file
#define VREFINT_CAL_VREF ( 3300U) /* Analog voltage reference (Vref+) value with which temperature sensor has been calibrated in production (tolerance: +-10 mV) (unit: mV). */
Since you are using 3V as Vref i am not sure if that's correct. It is usually 3.3 V
2. use these macros available in your stm32g4xx_ll_adc.h
for vref:
#define __LL_ADC_CALC_DATA_TO_VOLTAGE(__VREFANALOG_VOLTAGE__,\
__ADC_DATA__,\
__ADC_RESOLUTION__) \
((__ADC_DATA__) * (__VREFANALOG_VOLTAGE__) \
/ __LL_ADC_DIGITAL_SCALE(__ADC_RESOLUTION__) \
)
#define __LL_ADC_CALC_TEMPERATURE(__VREFANALOG_VOLTAGE__,\
__TEMPSENSOR_ADC_DATA__,\
__ADC_RESOLUTION__) \
(((( ((int32_t)((__LL_ADC_CONVERT_DATA_RESOLUTION((__TEMPSENSOR_ADC_DATA__), \
(__ADC_RESOLUTION__), \
LL_ADC_RESOLUTION_12B) \
* (__VREFANALOG_VOLTAGE__)) \
/ TEMPSENSOR_CAL_VREFANALOG) \
- (int32_t) *TEMPSENSOR_CAL1_ADDR) \
) * (int32_t)(TEMPSENSOR_CAL2_TEMP - TEMPSENSOR_CAL1_TEMP) \
) / (int32_t)((int32_t)*TEMPSENSOR_CAL2_ADDR - (int32_t)*TEMPSENSOR_CAL1_ADDR) \
) + TEMPSENSOR_CAL1_TEMP \
)
and calibrate adc using : HAL_ADCEx_Calibration_Start (&hadc)
3. As mentioned earlier, the internal temperature sensor does not measure the ambient chamber temperature; it measures the junction temperature of the microcontroller’s silicon die. Since the die naturally runs hotter than the surrounding environment, the internal reading will always be higher than the chamber temperature.
If you need to measure the actual chamber temperature, you’ll need an external temperature sensor (e.g., via I2C or another interface). Because you are comparing two different quantities (junction vs. ambient temperature), the percentage error you calculated is not valid.
2025-09-21 11:15 PM
As per your suggestions, I have tried all the recommended options:
I first tested with a 3.3V reference voltage, but I did not observe any significant changes.
Following your second suggestion, I used the lower-level command but this resulted in highly unexpected values.
Regarding your third point, I partly agree with the statement: "The internal temperature sensor does not measure the ambient chamber temperature; it measures the junction temperature of the microcontroller’s silicon die." I also understand that using an external temperature sensor would be the more reliable approach.
However, I would like to highlight an interesting observation. At 25 °C, the STM reports 29.25 °C; at 35 °C, it reports 36.68 °C; and at 65 °C, it reports 59.80 °C. This seems to contradict the statement "Since the die naturally runs hotter than the surrounding environment, the internal reading will always be higher than the chamber temperature."
In fact, based on my measurements, as the chamber temperature increases, the reported STM temperature tends to fall below the actual value. This suggests that the slope is not correct, which may be due to an issue in my code or potentially a hardware-related limitation of the MCU.
I would appreciate your opinion on this matter.
2025-09-21 11:23 PM
This is acceptable, but we at least expect linear behavior, which is not observed. A temperature offset or difference is understandable, but the lack of linearity is concerning.
From my observations:
At 25 °C, the STM reports 29.25 °C
At 35 °C, it reports 36.68 °C
At 65 °C, it reports 59.80 °C
This seems to contradict your explanation. Additionally, the response time of the internal temperature sensor is quite slow, which is very unexpected from such a powerful controller.
2025-09-21 11:25 PM
Okay, but can we at least expect linearity in temperature measurement?
2025-09-21 11:48 PM
The graph you posted seems pretty linear to me. You have a slope and an offset error, surely. Have you actually corrected your code for the high temperature calibration value?
2025-09-22 5:49 AM - edited 2025-09-22 5:49 AM
How long are you waiting before taking these readings? If the chip is embedded within a device, it can take a significant (up to ~2 hours) for the chip to reach steady state.
Perhaps post the full graph of ambient temp and junction temp over the course of the entire experiment.
> Additionally, the response time of the internal temperature sensor is quite slow, which is very unexpected from such a powerful controller.
The power of the controller doesn't affect the 2nd law of thermodynamics. Heat behaves the same regardless of device speed.
Did you fix the error in your previously posted code?
2025-09-22 8:25 PM
yes i fixed the error in previously posted code as per suggestions. Thankyou.
2025-09-23 8:54 PM
100% agrred.