性能不佳的原因是使用了浮点值。
我将展示如何摆脱它。
首先我们谈谈精度:
- TMP36 的温度范围为 500°C(从 -50°C 到 +450°C)。
- 模拟读取适用于从 0 到 1023(1024 个可能值)的 10 位。
所以精度是 500/1024。大约 0.5 °C。
因此,如果我们想在int 上编码温度,则此int 的次要位需要编码为 0.5°C 而不是 1°C。
示例:
int celciusTemperatureByHalfDegree = +40; // +20.0°C
int celciusTemperatureByHalfDegree = +41; // +20.5°C
int celciusTemperatureByHalfDegree = -10; // -5.0°C
int celciusTemperatureByHalfDegree = -15; // -5.5°C
我们看到:
celciusTemperatureByHalfDegree = celciusTemperature * 2
大概会有:
int reading = analogRead(PIN);
int voltage = (reading * 500) / 1024;
int celciusTemperature = voltage - 50;
int celciusTemperatureByHalfDegree = celciusTemperature * 2;
此时溢出和舍入问题导致此代码无用。
让我们简化一下:
int reading = (analogRead(PIN) * 500) / 1024;
int celciusTemperatureByHalfDegree = (reading - 50) * 2;
再说一遍:
int reading = (analogRead(PIN) * 500) / 512;
int celciusTemperatureByHalfDegree = reading - 100;
再说一遍:
int reading = (analogRead(PIN) * 125) / 128;
int celciusTemperatureByHalfDegree = reading - 100;
此时不再存在舍入问题。但是analogRead() 给出的输出介于 0 和 1023 之间。
并且1023 * 125 大于最大int16 (32,767),因此可能发生溢出。
这里我们将使用 125 = 5*25 和 128 = 4*32。
int reading = (analogRead(PIN) * 5 * 25) / (4 * 32);
int celciusTemperatureByHalfDegree = reading - 100;
会变成:
int reading = analogRead(PIN); // 0 to 1023
reading *= 5; // 0 to 5115 (no overflow)
reading /= 4; // 0 to 1278 (no overflow)
reading *= 25; // 0 to 31950 (no overflow)
reading /= 32; // 0 to 998
int celciusTemperatureByHalfDegree = reading - 100;
最后我们将使用这段代码来打印它:
// print the integer value of the temperature
Serial.print(celciusTemperatureByHalfDegree/2);
Serial.print(".");
// less significant bit code for "__.0" of "__.5"
Serial.print(celciusTemperatureByHalfDegree % 2 ? '5' : '0');
Serial.print("°C");