The BaseTemperature class provides a comprehensive temperature sensing abstraction that serves as
the unified interface for all thermal monitoring operations in the HardFOC system.
It supports multiple sensor types, calibration, alert thresholds,
and temperature unit conversions across different hardware implementations.
โจ Key Features
๐ก๏ธ Multi-Sensor Support - Support for various temperature sensor types
๐ฏ Hardware Abstraction - Works with internal and external temperature sensors
โก High-Precision Reading - Accurate temperature measurements with calibration
๐ Unit Conversion - Celsius, Fahrenheit, and Kelvin support
๐ Alert System - Configurable temperature thresholds and alerts
๐ก๏ธ Robust Error Handling - Comprehensive validation and error reporting
๐๏ธ Performance Optimized - Minimal overhead for real-time applications
๐ Platform Agnostic - Works across different MCU platforms
enumclasshf_temp_err_t:hf_u32_t{// Success codesTEMP_SUCCESS=0,// General errorsTEMP_ERR_FAILURE=1,TEMP_ERR_NOT_INITIALIZED=2,TEMP_ERR_ALREADY_INITIALIZED=3,TEMP_ERR_INVALID_PARAMETER=4,TEMP_ERR_NULL_POINTER=5,TEMP_ERR_OUT_OF_MEMORY=6,// Sensor specific errorsTEMP_ERR_SENSOR_NOT_AVAILABLE=7,TEMP_ERR_SENSOR_BUSY=8,TEMP_ERR_SENSOR_DISABLED=9,TEMP_ERR_SENSOR_NOT_READY=10,// Reading errorsTEMP_ERR_READ_FAILED=11,TEMP_ERR_READ_TIMEOUT=12,TEMP_ERR_READ_CRC_ERROR=13,TEMP_ERR_TEMPERATURE_OUT_OF_RANGE=14,// Calibration errorsTEMP_ERR_CALIBRATION_FAILED=15,TEMP_ERR_CALIBRATION_INVALID=16,TEMP_ERR_CALIBRATION_NOT_AVAILABLE=17,// Alert errorsTEMP_ERR_ALERT_NOT_SUPPORTED=18,TEMP_ERR_ALERT_THRESHOLD_INVALID=19,TEMP_ERR_ALERT_ALREADY_SET=20,// Communication errorsTEMP_ERR_COMMUNICATION_FAILURE=21,TEMP_ERR_DEVICE_NOT_RESPONDING=22,TEMP_ERR_BUS_ERROR=23,// System errorsTEMP_ERR_SYSTEM_ERROR=24,TEMP_ERR_PERMISSION_DENIED=25,TEMP_ERR_OPERATION_ABORTED=26};
๐ Error Code Categories
Category
Range
Description
|โโโ-|โโ-|โโโโ-|
Success
0
Successful operation
General
1-6
Basic initialization and parameter errors
Sensor
7-10
Sensor availability and status errors
Reading
11-14
Temperature measurement errors
Calibration
15-17
Calibration and accuracy errors
Alert
18-20
Temperature alert configuration errors
Communication
21-23
Sensor communication errors
System
24-26
System-level errors
๐ง Core API
๐ฏ Essential Methods
Initialization
1
2
3
4
5
6
7
8
9
10
11
/**
* @brief Ensure the temperature sensor is initialized
* @return hf_temp_err_t Error code
*/virtualhf_temp_err_tEnsureInitialized()=0;/**
* @brief Check if the temperature sensor is initialized
* @return bool True if initialized
*/virtualboolIsInitialized()const=0;
/**
* @brief Read temperature in Celsius
* @param temperature_c Output temperature in degrees Celsius
* @return hf_temp_err_t Error code
*/virtualhf_temp_err_tReadTemperature(float&temperature_c)=0;/**
* @brief Read temperature in Fahrenheit
* @param temperature_f Output temperature in degrees Fahrenheit
* @return hf_temp_err_t Error code
*/virtualhf_temp_err_tReadTemperatureF(float&temperature_f)=0;/**
* @brief Read temperature in Kelvin
* @param temperature_k Output temperature in Kelvin
* @return hf_temp_err_t Error code
*/virtualhf_temp_err_tReadTemperatureK(float&temperature_k)=0;
Alert Management
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* @brief Set temperature alert threshold
* @param threshold_c Threshold temperature in Celsius
* @param alert_type Type of alert (high/low/both)
* @return hf_temp_err_t Error code
*/virtualhf_temp_err_tSetAlertThreshold(floatthreshold_c,hf_temp_alert_type_talert_type)=0;/**
* @brief Check if alert condition is active
* @param alert_active Output alert status
* @return hf_temp_err_t Error code
*/virtualhf_temp_err_tIsAlertActive(bool&alert_active)=0;
enumclasshf_temp_alert_type_t:hf_u8_t{TEMP_ALERT_NONE=0,///< No alertTEMP_ALERT_HIGH=1,///< High temperature alertTEMP_ALERT_LOW=2,///< Low temperature alertTEMP_ALERT_BOTH=3///< Both high and low alerts};
๐ Sensor Information
1
2
3
4
5
6
7
8
9
10
11
structhf_temp_sensor_info_t{hf_u32_tsensor_id;///< Unique sensor identifiercharsensor_name[32];///< Sensor name stringfloatmin_temperature_c;///< Minimum measurable temperaturefloatmax_temperature_c;///< Maximum measurable temperaturefloatresolution_c;///< Temperature resolutionfloataccuracy_c;///< Temperature accuracyhf_u32_tresponse_time_ms;///< Sensor response timeboolsupports_alerts;///< Alert capabilityboolsupports_continuous;///< Continuous reading capability};
๐ Temperature Statistics
1
2
3
4
5
6
7
8
9
10
structhf_temp_statistics_t{hf_u32_ttotal_reads;///< Total number of readshf_u32_tsuccessful_reads;///< Successful reads counthf_u32_tfailed_reads;///< Failed reads countfloatmin_temperature_c;///< Minimum recorded temperaturefloatmax_temperature_c;///< Maximum recorded temperaturefloatavg_temperature_c;///< Average temperaturehf_u32_tlast_read_time_ms;///< Last reading timestamphf_u32_ttotal_alerts_triggered;///< Total alerts triggered};
/**
* @brief Convert Celsius to Fahrenheit
* @param celsius Temperature in Celsius
* @return float Temperature in Fahrenheit
*/staticinlinefloatCelsiusToFahrenheit(floatcelsius){return(celsius*9.0f/5.0f)+32.0f;}/**
* @brief Convert Celsius to Kelvin
* @param celsius Temperature in Celsius
* @return float Temperature in Kelvin
*/staticinlinefloatCelsiusToKelvin(floatcelsius){returncelsius+273.15f;}/**
* @brief Convert Fahrenheit to Celsius
* @param fahrenheit Temperature in Fahrenheit
* @return float Temperature in Celsius
*/staticinlinefloatFahrenheitToCelsius(floatfahrenheit){return(fahrenheit-32.0f)*5.0f/9.0f;}
#include"inc/external/Ds18b20Temperature.h"classTemperatureAlertSystem{private:Ds18b20Temperaturetemp_sensor*;boolalert_callback_registered*;public:TemperatureAlertSystem(BaseGpio*one_wire_pin):temp_sensor*(one_wire_pin),alert_callback_registered*(false){}boolsetup_thermal_protection(){// Initialize sensorif(temp_sensor*.EnsureInitialized()!=hf_temp_err_t::TEMP_SUCCESS){returnfalse;}// Set high temperature alert at 85ยฐCif(temp_sensor*.SetAlertThreshold(85.0f,hf_temp_alert_type_t::TEMP_ALERT_HIGH)!=hf_temp_err_t::TEMP_SUCCESS){returnfalse;}// Set low temperature alert at -10ยฐCif(temp_sensor*.SetAlertThreshold(-10.0f,hf_temp_alert_type_t::TEMP_ALERT_LOW)!=hf_temp_err_t::TEMP_SUCCESS){returnfalse;}printf("๐ก๏ธ Thermal protection enabled (-10ยฐC to 85ยฐC)\n");returntrue;}voidmonitor_alerts(){boolalert_active;if(temp_sensor*.IsAlertActive(alert_active)==hf_temp_err_t::TEMP_SUCCESS){if(alert_active){floatcurrent_temp;temp_sensor*.ReadTemperature(current_temp);printf("๐จ TEMPERATURE ALERT: %.2fยฐC\n",current_temp);// Implement emergency responseif(current_temp>85.0f){printf("โ ๏ธ OVERHEATING - Shutting down system\n");emergency_shutdown();}elseif(current_temp<-10.0f){printf("โ ๏ธ FREEZING - Activating heater\n");activate_heater();}}}}private:voidemergency_shutdown(){// Implement emergency shutdown logic}voidactivate_heater(){// Implement heater activation logic}};
#include"inc/external/Lm35Temperature.h"
#include"inc/external/Ntc10kTemperature.h"classMultiSensorTempSystem{private:EspTemperatureinternal_temp*;Lm35Temperatureambient_temp*;Ntc10kTemperaturemotor_temp*;structTemperatureReading{floatinternal;floatambient;floatmotor;hf_u32_ttimestamp;};public:MultiSensorTempSystem(BaseAdc*adc):ambient_temp*(adc,ADC_CHANNEL_0),motor_temp*(adc,ADC_CHANNEL_1){}boolinitialize(){boolsuccess=true;success&=(internal_temp*.EnsureInitialized()==hf_temp_err_t::TEMP_SUCCESS);success&=(ambient_temp*.EnsureInitialized()==hf_temp_err_t::TEMP_SUCCESS);success&=(motor_temp*.EnsureInitialized()==hf_temp_err_t::TEMP_SUCCESS);if(success){printf("๐ก๏ธ Multi-sensor temperature system initialized\n");}returnsuccess;}TemperatureReadingread_all_temperatures(){TemperatureReadingreading={};reading.timestamp=esp_timer_get_time()/1000;// Convert to ms// Read internal temperatureif(internal_temp*.ReadTemperature(reading.internal)!=hf_temp_err_t::TEMP_SUCCESS){reading.internal=NAN;}// Read ambient temperatureif(ambient_temp*.ReadTemperature(reading.ambient)!=hf_temp_err_t::TEMP_SUCCESS){reading.ambient=NAN;}// Read motor temperatureif(motor_temp*.ReadTemperature(reading.motor)!=hf_temp_err_t::TEMP_SUCCESS){reading.motor=NAN;}returnreading;}voidlog_temperature_data(){TemperatureReadingreading=read_all_temperatures();printf("๐ Temperature Report [%lu ms]:\n",reading.timestamp);printf(" Internal: %.2fยฐC\n",reading.internal);printf(" Ambient: %.2fยฐC\n",reading.ambient);printf(" Motor: %.2fยฐC\n",reading.motor);// Check for thermal issuesif(reading.motor>80.0f){printf("โ ๏ธ Motor overheating detected!\n");}if(reading.internal>70.0f){printf("โ ๏ธ MCU overheating detected!\n");}}voidstart_continuous_monitoring(hf_u32_tinterval_ms=5000){// Start continuous reading on all sensorsinternal_temp*.StartContinuousReading(interval_ms);ambient_temp*.StartContinuousReading(interval_ms);motor_temp*.StartContinuousReading(interval_ms);printf("๐ Continuous temperature monitoring started (%lu ms interval)\n",interval_ms);}};
๐งช Best Practices
โ Recommended Practices
๐ฏ Initialize Early
1
2
3
4
5
// Initialize temperature sensors during system startupif(temp_sensor.EnsureInitialized()!=hf_temp_err_t::TEMP_SUCCESS){printf("โ Temperature sensor initialization failed\n");// Handle initialization failure}
๐ก๏ธ Use Appropriate Units
1
2
3
4
5
6
7
// Be consistent with temperature unitsfloattemp_c;temp_sensor.ReadTemperature(temp_c);// Always in Celsius// Convert when displaying to usersfloattemp_f=BaseTemperature::CelsiusToFahrenheit(temp_c);printf("Temperature: %.1fยฐF\n",temp_f);
๐จ Implement Thermal Protection
1
2
3
// Set appropriate alert thresholdstemp_sensor.SetAlertThreshold(85.0f,hf_temp_alert_type_t::TEMP_ALERT_HIGH);temp_sensor.SetAlertThreshold(-10.0f,hf_temp_alert_type_t::TEMP_ALERT_LOW);
// BAD: Mixing temperature unitsfloattemp_f;temp_sensor.ReadTemperature(temp_f);// This returns Celsius!// GOOD: Use correct methods for unitsfloattemp_c,temp_f;temp_sensor.ReadTemperature(temp_c);// Celsiustemp_sensor.ReadTemperatureF(temp_f);// Fahrenheit
๐ซ Ignoring Sensor Limitations
1
2
3
4
5
6
7
8
9
10
11
// BAD: Not checking sensor rangeif(temperature>100.0f){// May be invalid for some sensors}// GOOD: Check sensor specificationshf_temp_sensor_info_tinfo;temp_sensor.GetSensorInfo(info);if(temperature>info.max_temperature_c){printf("โ ๏ธ Temperature exceeds sensor range\n");}
๐ฏ Performance Tips
โก Use Continuous Reading for High-Frequency Monitoring
1
2
// Start continuous reading for frequent updatestemp_sensor.StartContinuousReading(100);// 100ms interval
๐ Batch Multiple Sensor Reads
1
2
3
4
5
// Read multiple sensors together for efficiencyfloattemps[3];sensor1.ReadTemperature(temps[0]);sensor2.ReadTemperature(temps[1]);sensor3.ReadTemperature(temps[2]);
๐ Use Statistics for Health Monitoring
1
2
3
// Monitor sensor performance over timehf_temp_statistics_tstats;temp_sensor.GetStatistics(stats);
๐ก๏ธ Professional Temperature Monitoring for Critical Applications
Ensuring thermal safety and optimal performance across all operating conditions