# Import the necessary libraries
import time, math, machine
from i2c_lcd import LiquidCrystalI2C
# Define the beta value of the thermistor, typically provided in the datasheet
beta     = 3950
adc_pin  = 35
LCD_COLS = 16
LCD_ROWS = 2
LED = machine.Pin(4, machine.Pin.OUT)
# Intantiate the lcd object from the I2C class
i2c = machine.SoftI2C(sda=machine.Pin(21), scl=machine.Pin(22))
lcd = LiquidCrystalI2C(i2c, 0x27, LCD_COLS, LCD_ROWS)
# Create an ADC object (thermistor)
thermistor = machine.ADC(machine.Pin(adc_pin, machine.Pin.IN))
# Set the attenuation and bit width
thermistor.atten(thermistor.ATTN_11DB)
thermistor.width(thermistor.WIDTH_12BIT)
# Start an infinite loop to continuously monitor the temperature
while True:
    # Read the adc values 
    Vr = thermistor.read()
    # Calculate the resistance of the thermistor based on the measured voltage
    Rt =  Vr/4
    # Use the beta parameter and resistance value to calculate the temperature in Celsius
    temp_Cel = 1 / (math.log(1 / (1023/ Rt - 1)) / beta + 1.0 / 298.15) - 273.15
    # Convert to Fahrenheit
    temp_Fah = temp_Cel * 1.8 + 32
    if(temp_Cel>65):
        LED.value(1)
    elif(temp_Cel>=40 and temp_Cel<45):
        LED.on()
        time.sleep_ms(500)
        LED.off()
    elif(temp_Cel>=45 and temp_Cel<50):
        LED.on()
        time.sleep_ms(400)
        LED.off()
    elif(temp_Cel>=50 and temp_Cel<55):
        LED.value(1)
        time.sleep_ms(300)
        LED.value(0)
    elif(temp_Cel>=55 and temp_Cel<60) :
        LED.value(1)
        time.sleep_ms(200)
        LED.value(0)
    elif(temp_Cel>=60 and temp_Cel<65):
        LED.value(1)
        time.sleep(0.1)
        LED.value(0)
    else:
        LED.value(0)
    # Display the temperature values in both Celsius and Fahrenheit
    lcd.backlight()
    lcd.set_cursor(0, 0)
    lcd.print('Cel: %.2f \xDFC \n' % temp_Cel)
    lcd.set_cursor(0, 1)
    lcd.print('Fah: %.2f \xDFF' % temp_Fah)
    lcd.display()
    time.sleep(.1)