本帖最后由 shipeng1989 于 2025-11-6 11:17 编辑
在嵌入式软件开发中经常会遇到NTC温度换算的功能需求,对于测温要求不高的应用可以采用查表法实现,但是查表法需要繁琐的数据录入工作,其实关于NTC温度换算有一种普适方法可以解决所有的NTC温度换算问题,不同的NTC只需要修改一下相关参数即可适用此套算法。关于这个厉害的算法我也是前几年偶然在网上找到的,当时还收藏了链接只是现在已经找不到了,刚好最近又碰到了NTC温度换算的问题才想起来这个算法很重要,于是决定把它做一个详细记录并分享出来。
- //K0C: 0 Celsius = 273.15 Kelvin
- #define K0C 273.15F
- //T25: 25 Celsius = 298.15 Kelvin
- #define T25 298.15F
- //R25: NTC resistance value(KOhm) at 25 celsius
- #define R25 10.0F
- //LNR25=ln(R25)=ln10=2.30258509
- #define LNR25 2.302585F
- //BNTC: the B value of NTC
- #define BNTC 3455.0F
- //RPU: PULL-UP resistance(KOhm) of NTC
- #define RPU 33.0F
- //MAX_ADC: MAX VALUE OF ADC
- #define MAX_ADC 4096
- //自然对数计算函数
- static double myln(double a)
- {
- //我们取了前511+1项来估算,N值越大计算结果越精确
- #define N 511
- int k,nk;
- double x,xx,y;
- x = (a-1)/(a+1);
- xx = x*x;
- nk = 2*N+1;
- y = 1.0/nk;
- for(k=N;k>0;k--)
- {
- nk = nk - 2;
- y = 1.0/nk+xx*y;
-
- }
- return 2.0*x*y;
- }
- //B=(ln R25 - ln Rntc)/(1/T25 - 1/Tn);(Tn is the kelvin temp)
- static float Get_Kelvin_Temperature(float Rntc)
- {
- float N1,N2,N3;
- if (Rntc==0)return 899.0f;
- N1 = (float)((LNR25-myln((double)Rntc))/BNTC);//LNR25<-->myln(R25)
- N2 = 1/T25 - N1;
- N3 = 1/N2;
- return N3;
- }
- float ADV2CelsiusTemp(uint16_t adv)
- {
- float ctemp,Rntc = RPU*adv/(MAX_ADC-adv);
- ctemp = Get_Kelvin_Temperature(Rntc)-K0C;
- return ctemp;
- }
|