| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- #include "NtcThermistor.h"
- // 构造函数
- NtcThermistor::NtcThermistor(int pin1, int pin2, int pin3,
- float referenceResistance,
- float ntcNominalResistance,
- float ntcBetaValue,
- float referenceTemperature,
- int adcResolution) :
- _pin1(pin1),
- _pin2(pin2),
- _pin3(pin3),
- _referenceResistance(referenceResistance),
- _ntcNominalResistance(ntcNominalResistance),
- _ntcBetaValue(ntcBetaValue),
- _referenceTemperature(referenceTemperature + 273.15), // 转换为开尔文
- _adcResolution(adcResolution) {
-
- // 初始化温度值
- _temperature1 = 0.0;
- _temperature2 = 0.0;
- _temperature3 = 0.0;
-
- // 配置引脚为输入
- pinMode(_pin1, INPUT);
- pinMode(_pin2, INPUT);
- pinMode(_pin3, INPUT);
- }
- // 读取单个NTC温度(优化版本)
- float NtcThermistor::readTemperature(int pin) {
- // 多次采样取平均,减少噪声
- int adcSum = 0;
- for (int i = 0; i < 20; i++) {
- adcSum += analogRead(pin);
- delayMicroseconds(100);
- }
- int adcValue = adcSum / 20;
-
- // 调试:打印ADC原始值(方便排查问题)
- Serial.print("Pin ");
- Serial.print(pin);
- Serial.print(" ADC: ");
- Serial.print(adcValue);
-
- // 防止除以零错误(放宽范围,避免误判)
- if (adcValue < 5 || adcValue > _adcResolution - 5) {
- Serial.println(" -> 超出范围");
- return -273.15;
- }
-
- // 计算NTC电阻(关键公式修正)
- // 注意:这里使用(float)强制转换,避免整数除法导致精度丢失
- float resistance = _referenceResistance * ((float)_adcResolution / adcValue - 1.0);
- Serial.print(" | 电阻: ");
- Serial.print(resistance);
- Serial.print("Ω");
-
- // 使用B参数方程计算温度(修正计算顺序)
- float steinhart;
- steinhart = resistance / _ntcNominalResistance; // (R/R0)
- steinhart = log(steinhart); // ln(R/R0)
- steinhart /= _ntcBetaValue; // 1/B * ln(R/R0)
- steinhart += 1.0 / _referenceTemperature; // + 1/T0 (T0为25℃的开尔文温度)
- steinhart = 1.0 / steinhart; // 计算得到开尔文温度
- float celsius = steinhart - 273.15; // 转换为摄氏度
-
- Serial.print(" | 温度: ");
- Serial.println(celsius);
-
- return celsius;
- }
- // 更新所有温度读数
- void NtcThermistor::updateTemperatures() {
- _temperature1 = readTemperature(_pin1);
- _temperature2 = readTemperature(_pin2);
- _temperature3 = readTemperature(_pin3);
- }
- // 获取温度值
- float NtcThermistor::getTemperature1() {
- return _temperature1;
- }
- float NtcThermistor::getTemperature2() {
- return _temperature2;
- }
- float NtcThermistor::getTemperature3() {
- return _temperature3;
- }
- // 获取格式化的温度字符串
- String NtcThermistor::getTemperature1String() {
- return String(_temperature1, 1) + " °C";
- }
- String NtcThermistor::getTemperature2String() {
- return String(_temperature2, 1) + " °C";
- }
- String NtcThermistor::getTemperature3String() {
- return String(_temperature3, 1) + " °C";
- }
-
|