from machine import Pin, I2C, ADC
import ssd1306, time
from math import log

# ESP32 Pin assignment 
i2c = I2C(0, scl=Pin(22), sda=Pin(21))

temp=ADC(Pin(27))

oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)

def adc_to_celsius(raw):
    BETA=3950
    celsius = 1 / (log(1 / (65535 / raw - 1)) / BETA + 1.0 / 298.15) - 273.15
    return celsius


def show_value(raw):
    oled.text("Temperature (C): ", 0, 0)
    oled.text(str(raw), 0, 20)
    oled.show()

def clear():
    oled.fill(0)        #per cancellare riempiamo con colore nero (0)
    oled.show()

prev_temp = temp.read_u16()
show_value(adc_to_celsius(prev_temp))


while True:
    c_temp = temp.read_u16()
    if c_temp != prev_temp:
        clear()
        show_value(adc_to_celsius(c_temp))
        prev_temp=c_temp