ESP32 NTC测温代码,它包括了温度补偿和校准功能,可以提高测量精度
以下是一个更加完整的ESP32 NTC测温代码,它包括了温度补偿和校准功能,可以提高测量精度。
以下是一个更加完整的ESP32 NTC测温代码,它包括了温度补偿和校准功能,可以提高测量精度。
// 定义NTC电阻和电压分压电阻
#define R_NTC 10000.0
#define R_DIV 10000.0
// 定义NTC电阻的参考温度和参考电阻值
#define NTC_REF_TEMP 25.0
#define NTC_REF_RES 10000.0
// 定义温度补偿参数
#define TEMP_COMP_BETA 3892.0
#define TEMP_COMP_REF_RES 10000.0
// 定义校准参数
#define CALIBRATION_OFFSET 0.0
#define CALIBRATION_SCALE 1.0
void setup() {
Serial.begin(9600);
while (!Serial) {
delay(10);
}
}
void loop() {
// 读取NTC电阻对应的电压
float voltage = analogRead(A0) * 3.3 / 4095.0;
// 计算NTC电阻的电阻值
float r_ntc = R_DIV * voltage / (3.3 - voltage);
// 计算NTC电阻的温度
float beta = 3950.0; // NTC的Beta值
float steinhart = r_ntc / R_NTC; // 计算Steinhart-Hart方程中的变量
steinhart = log(steinhart);
steinhart /= beta;
steinhart += 1.0 / (NTC_REF_TEMP + 273.15);
steinhart = 1.0 / steinhart;
float ntc_temp = steinhart - 273.15; // 转化为摄氏度
// 温度补偿
float temp_comp_res = TEMP_COMP_REF_RES * exp(-TEMP_COMP_BETA / (NTC_REF_TEMP + 273.15));
float temp_comp_ratio = temp_comp_res / (temp_comp_res + r_ntc);
ntc_temp = (ntc_temp - NTC_REF_TEMP) / (1.0 + temp_comp_ratio);
// 校准
ntc_temp = ntc_temp * CALIBRATION_SCALE + CALIBRATION_OFFSET;
// 输出温度
Serial.print("NTC temperature: ");
Serial.print(ntc_temp);
Serial.println(" °C");
delay(1000);
}

