本帖最后由 lsrly 于 2023-11-17 10:59 编辑
(用啥学啥)NTC热敏电阻二次查询法
一,定义变量数组
1.定义NTC 温度把对应的ADC值(这个要根据你所用的串联电阻和NTC及单片机ADC范围来计算)
static const uint32_t NTC_ADC_Table[] =// 5K NTC ADC值
{
10228,9865,9513,9170,8838,8515,8203,7900,7607,7323,
7050,6785,6530,6283,6044,5817,5596,5383,5179,4982,
4792,4610,4435,4266,4104,3948,3799,3655,3517,3385,
3257,3135,3021,2905,2797,2693,2593,2497,2405,2317,
2233,2151,2073,1998,1926,1857,1790,1726,1665,1606,
1550,1495,1443,1393,1344,1298,1253,1210,1169,1130,
1091,1054,1019,985,952,921,891,862,833,806,
780,755,731,707,685,663,642,622,602,584,
635,548,531,515,499,484,470,455,442,429,
416,404,392,380,369,358,348,338,328,319,
310,301,293,284,276,269,261,254,247,240,
233,227,221,215,209,203,198,193,188,183,
};
2.定义NTC所对应的温度
static const sint16 NTC_temperature_table[] = //温度表
{
-20, -19, -18, -17, -16, -15, -14, -13, -12, -11,
-10, -9, -8, -7, -6, -5, -4, -3, -2, -1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
90, 91, 92, 93, 94, 95, 96, 97, 98, 99,
};
二,获取ADC值
uint32_t get_ntc()
{
uint32_t TMVale = 0;
for (int i = 0; i < 10; i++)
{
TMVale += analogRead(A0);
delay(10);
}
TMVale = TMVale / 10;
return TMVale;
}
三,根据ADC使用二次查询法查ADC值在NTC_ADC_Table[]表的位置
float get_temperature()
{
float temperature=0.0;
float temperxiaoxu=0.0;
uint16_t start=0,end=120,middle=0;
/********获取数组的长度**********/
//end = sizeof( NTC_ADC_Table) / sizeof( NTC_ADC_Table[0]);
uint32_t ntcvalue = get_ntc()*10; // 获取NTC的ADC值
//float resistance = (float)(1023 - ntcvalue) * 10000 / ntcvalue; // 计算NTC的电阻值
Serial.print( "adc");
Serial.println(ntcvalue);
while (start <= end)
{
Serial.print( "start=");
Serial.println(start);
Serial.print( "end=");
Serial.println(end);
middle = (start + end)/2; //折半
if(ntcvalue== NTC_ADC_Table[middle])break; //值相等,说明查到了,退出循环
if((ntcvalue< NTC_ADC_Table[middle])&&(ntcvalue> NTC_ADC_Table[middle+1]))break;//在两者之间退出循环
if (ntcvalue > NTC_ADC_Table[middle]) //当前值大于数组中间数值 说明要查找的数在前一半
{
end= middle - 1; //前一半的数组头不变 数组尾重新分配
}
else if (ntcvalue < NTC_ADC_Table[middle])// //当前AD值小于数组中间数值 说明要查找的数在后一半
{
start = middle + 1; //前一半的数组尾不变 数组头重新分配
}
}
Serial.print( "start=");
Serial.println(start);
Serial.print( "end=");
Serial.println(end);
Serial.print( "middle=");
Serial.println(middle);
temperxiaoxu=(NTC_ADC_Table[middle]-NTC_ADC_Table[middle+1]);
temperxiaoxu=(NTC_ADC_Table[middle]-ntcvalue)/temperxiaoxu;
temperature=NTC_temperature_table[middle]+temperxiaoxu;
return temperature;
}
四,调用get_temperature()获得对应的温度
|