Skip to content

Instantly share code, notes, and snippets.

@fbaeuerlein
Created May 27, 2019 07:11
Show Gist options
  • Save fbaeuerlein/8292eeb7d6a7339dcda9e41a47a93ef8 to your computer and use it in GitHub Desktop.
Save fbaeuerlein/8292eeb7d6a7339dcda9e41a47a93ef8 to your computer and use it in GitHub Desktop.
Python fitting of Steinhart-Hart equation for thermal resistors (returns the temperature for specified resistance)
# Details:
# https://en.wikipedia.org/wiki/Steinhart%E2%80%93Hart_equation
# https://de.wikipedia.org/wiki/Steinhart-Hart-Gleichung
# Fitting of the four coefficient equation
import csv
import numpy
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
x = []
y = []
# read data from CSV file
with open('data.csv', newline='') as csvfile:
datareader = csv.reader(csvfile, delimiter=',')
for row in datareader:
#print(row)
t = float(row[0])
x.append(float(row[2])*1000) # resistance values in kOhm
y.append(t + 273.15) # convert temperature to absolute temperature
# Steinhart-Hart-Equation
def f(x, a0, a1, a2, a3):
return 1. / (a0 + a1 * numpy.log(x) + a2 * numpy.power(numpy.log(x),2) + a3 * numpy.power(numpy.log(x),3))
# Do the fit with initial values (needed, otherwise no meaningful result)
params, cov = curve_fit(f, x, y, p0=[1e-4, 1e-4, 1e-4, 1e-4])
print("Coeffs: {}".format(params))
# generate curve with fit result
y2 = []
for v in x:
y2.append(f(v, params[0], params[1], params[2], params[3]))
# plot original data and result
plt.plot(x, y)
plt.plot(x, y2)
#plt.plot(x, numpy.abs(numpy.subtract(y, y2))) # error values
plt.show()
@mirtcho
Copy link

mirtcho commented Feb 2, 2022

Simple and effective tool. Forked from here and added NTC self heating compensation.

@fbaeuerlein
Copy link
Author

Thanks for the feedback! I also made some jupyter notebook: https://github.com/fbaeuerlein/jupyter-steinhart-hart

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment