1#!/usr/bin/env python3 2 3# Copyright (c) 2023 Google LLC 4# SPDX-License-Identifier: Apache-2.0 5 6""" 7Zephyr's NTC Thermistor DTS Table generator 8########################################### 9 10This script can be used to generate an NTC thermistor DTS node with a 11"zephyr,compensation-table" property. This uses the Beta Parameter Equation 12 13https://devxplained.eu/en/blog/temperature-measurement-with-ntcs#beta-parameter-equation 14 15Look-up the following electrical characteristics in the thermistor's data sheet: 16 Nominal resistance (R25) - The thermistor's resistance measured at 25C 17 Beta value (25/85) - This is the resistance value at 25C and at 85C 18 19Usage:: 20 21 python3 ntc_thermistor_table.py \ 22 -r25 10000 \ 23 -b 3974 > thermistor.dtsi 24 25""" 26 27import argparse 28import os 29import math 30 31def c_to_k(c: float): 32 """ Convert Celicius to Kelvin """ 33 return c + 273.15 34 35def beta_equation_calc_resistance(r25, beta, temp_c): 36 t0_kelvin = c_to_k(25) 37 38 exp = beta * ((1 / c_to_k(temp_c)) - (1 / t0_kelvin)) 39 resistance = r25 * math.exp(exp) 40 41 return resistance 42 43 44def main( 45 r25: float, beta: float, interval: int, temp_init: int, temp_final: int 46) -> None: 47 temps_range = range(temp_init, temp_final + interval - 1, interval) 48 49 print(f"/* NTC Thermistor Table Generated with {os.path.basename(__file__)} */\n") 50 print( 51 f"thermistor_R25_{int(r25)}_B_{int(beta)}: thermistor-R25-{int(r25)}-B-{int(beta)} {{" 52 ) 53 54 table = [] 55 for temp in temps_range: 56 resistance = beta_equation_calc_resistance(r25, beta, temp) 57 table.append(f"<({int(temp)}) {int(resistance)}>") 58 59 tbl_string = ',\n\t\t'.join(table) 60 print(f"\tzephyr,compensation-table = {tbl_string};") 61 print(f"}};") 62 63 64if __name__ == "__main__": 65 parser = argparse.ArgumentParser("NTC Thermistor generator", allow_abbrev=False) 66 parser.add_argument( 67 "-r25", type=float, required=True, help="Nominal resistance of thermistor" 68 ) 69 parser.add_argument( 70 "-b", "--beta", type=float, required=True, help="Beta(25/85) value" 71 ) 72 parser.add_argument( 73 "-i", 74 "--interval", 75 type=int, 76 required=False, 77 help="Generated table interval", 78 default=10, 79 ) 80 parser.add_argument( 81 "-ti", 82 type=int, 83 required=False, 84 help="First temperature", 85 default=-25, 86 ) 87 parser.add_argument( 88 "-tf", 89 type=int, 90 required=False, 91 help="Final temperature", 92 default=125, 93 ) 94 args = parser.parse_args() 95 96 main(args.r25, args.beta, args.interval, args.ti, args.tf) 97