99#include "freertos/FreeRTOS.h"
1010#include "esp_private/sar_periph_ctrl.h"
1111#include "esp_log.h"
12+ #include "esp_timer.h"
1213
1314#if SOC_TEMP_SENSOR_SUPPORTED
1415#include "hal/temperature_sensor_ll.h"
@@ -40,17 +41,22 @@ static const char *TAG_TSENS = "temperature_sensor";
4041# define SAR_PERIPH_CTRL_COMMON_FN_ATTR
4142#endif
4243
44+ #define TSENS_LINE_REGRESSION_US (200)
45+
4346static int s_record_min = INT_NOT_USED ;
4447static int s_record_max = INT_NOT_USED ;
4548static int s_temperature_sensor_power_cnt ;
49+ static bool s_first_temp_read = false;
4650
4751static uint8_t s_tsens_idx = 2 ; // Index for temperature attribute, set 2(middle) as default value
52+ static int64_t timer1 = 0 ;
4853
4954void temperature_sensor_power_acquire (void )
5055{
5156 esp_os_enter_critical (& rtc_spinlock );
5257 s_temperature_sensor_power_cnt ++ ;
5358 if (s_temperature_sensor_power_cnt == 1 ) {
59+ s_first_temp_read = true;
5460 regi2c_saradc_enable ();
5561#if !SOC_TSENS_IS_INDEPENDENT_FROM_ADC
5662 adc_apb_periph_claim ();
@@ -60,6 +66,9 @@ void temperature_sensor_power_acquire(void)
6066 temperature_sensor_ll_reset_module ();
6167 }
6268 temperature_sensor_ll_enable (true);
69+ // Set the range as recorded.
70+ temperature_sensor_ll_set_range (temperature_sensor_attributes [s_tsens_idx ].reg_val );
71+ timer1 = esp_timer_get_time ();
6372 }
6473 esp_os_exit_critical (& rtc_spinlock );
6574}
@@ -101,6 +110,18 @@ int16_t temp_sensor_get_raw_value(bool *range_changed)
101110{
102111 esp_os_enter_critical (& rtc_spinlock );
103112
113+ // When this is the first time reading a value, check whether the time here minus the
114+ // initialization time is greater than 200 microseconds (the time for linear regression).
115+ // If it is less than 200 microseconds, continue waiting here.
116+ if (s_first_temp_read == true) {
117+ int64_t timer2 = esp_timer_get_time ();
118+ int64_t diff = timer2 - timer1 ;
119+ if (diff < TSENS_LINE_REGRESSION_US ) {
120+ esp_rom_delay_us (TSENS_LINE_REGRESSION_US - diff );
121+ }
122+ s_first_temp_read = false;
123+ }
124+
104125 int degree = temperature_sensor_get_raw_value ();
105126 uint8_t temperature_dac ;
106127
0 commit comments