# Measure temperature with ESP32 , a Thermistor and MicroPython
# -------------------------------------------------------------------
# The used Thermistor is a NTC (Negative Temperature Coefficient).
# In a NTC Thermistor, resistance decreases as the temperature rises.
# There is a non-linear relationship between resistance and temperature.
#
# The Display ssd1306 is connected with the serial bus I2C .
# I2C stands for Inter-Integrated Circuit.
#
# During the temperature measurement with a NTC a led is switched on.
# -------------------------------------------------------------------
# libraries
from machine import ADC, Pin, I2C
from time import sleep
import ssd1306
from math import log
# a warm welcome :)
print("Hello, ESP32!")
# ESP32 Pin assignment for the LED.
# the Pin is defined as output to switch the LED on.
# the LED is protected with a 1 kOhm resistor
led = Pin(15, Pin.OUT)
# ESP32 Pin assignment and size definitions for OLED display (ssd1306)
# I2C : serial bus with SCL (serial clock) and SDA (serial data)
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
# ESP32 Pin assignment for the Thermistor, using the integrated
# ADC (Analog Digital Converter);
# the signal is not attenuated (ATTN_0DB)
ntc_pin = ADC(Pin(35))
ntc_pin.atten(ADC.ATTN_0DB)
# Beta Coefficient of the Thermistor
beta = 3950.0
# write a first text on the OLED display
oled.text('Hello, David!', 10, 10)
oled.show()
sleep(3)
# measure the temperature every second in an endless loop
while True:
# begin new measurement : switch led on
led.on()
# delete old content and initialize OLED display
oled.init_display()
# read thermistor and calculate temperature in Celsius
# resolution is 12 bit (4095)
# calculate Kelvin to Celsius : 273.15
ntc_data = ntc_pin.read()
print('ntc_data = ' + str(ntc_data))
temp = 1.0 / (log(1.0 / (4095.0 / ntc_data - 1)) / beta + 1.0 / 298.15) - 273.15;
print('temp = ' + str(temp))
print('---------------------------')
# display the measured temperature in Celsius in Console and OLED display
oled.text(str(temp), 30, 30)
oled.show()
# end of measurement : switch led off
led.off()
# wait 1 second before new measurement
sleep(1)