3d打印中NTC 温度传感器是用的查询表法进行温度测量,如下是示例
#define NTC_PIN A0 // NTC接在A0口上// NTC查询表// 温度(°C) 电阻(Ω)// -50 10000// -40 7596// -30 5741// -20 4295// -10 3183// 0 2392// 10 1796// 20 1365// 30 1019// 40 761// 50 557// 60 408// 70 298// 80 221// 90 159// 100 113
int resistanceTable[15] = {10000, 7596, 5741, 4295, 3183, 2392, 1796, 1365, 1019, 761, 557, 408, 298, 221, 159};
int temperatureTable[15] = {-50, -40, -30, -20, -10, 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
void setup() {
Serial.begin(9600); // 打开串口,波特率为9600
}
void loop() {
int ntcValue = analogRead(NTC_PIN); // 读取NTC的电阻值float resistance = (float)(1023-ntcValue)*10000/ntcValue; // 计算NTC的电阻
int temperature; // 声明温度变量// 使用二分法查询表查找温度
int left = 0;
int right = 14;
while (left <= right) {
int mid = (left + right) / 2;
if (resistance < resistanceTable[mid]) {
right = mid - 1;
} else if (resistance > resistanceTable[mid]) {
left = mid + 1;
} else {
temperature = temperatureTable[mid];
break;
}
}
if (left > right) { // 如果没有找到,则使用线性插值计算float slope = (float)(temperatureTable[left] - temperatureTable[right]) / (resistanceTable[left] - resistanceTable[right]);
temperature = temperatureTable[right] + slope * (resistance - resistanceTable[right]);
}
Serial.println(temperature); // 将温度值发送到串口delay(1000); // 等待1秒
}
在这个程序中
在这个程序中,我们首先读取 NTC 的电阻值,然后使用二分法查询表查找温度。如果找到了匹配的电阻值,则直接使用表中的温度值。如果没有找到,则使用线性插值的方法计算温度值。最后,我们将温度值发送到串口。
使用查询表的方法可以提高测量精度,因为表中的数据是经过校准的,但是同时也会增加程序的复杂度,需要消耗额外的存储空间。如果空间有限,可以考虑使用更简单的测量方法,比如基于线性关系的公式。