import machine
import utime
import ssd1306
import max31855

#Setup I2C for OLED (GP0 = SDA, GP1 = SCL)
i2c = machine.I2C(0, sda=machine.Pin(0), scl=machine.Pin(1), freq=400000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)

#Setup SPI for MAX31855 (GP16=SO, GP17=CS, GP18=SCK)
spi = machine.SPI(0, baudrate=1000000, polarity=0, phase=0, 
                  sck=machine.Pin(18), mosi=None, miso=machine.Pin(16))
cs = machine.Pin(17, machine.Pin.OUT)
sensor = max31855.MAX31855(spi, cs)

def display_temp(celsius):
    oled.fill(0)
    oled.text("PI-THERMOMETER", 10, 0)
    oled.text("----------------", 0, 15)
    
    fahrenheit = (celsius * 9/5) + 32
    
    oled.text("Temp: {:.1f} F".format(fahrenheit), 0, 40)
    oled.text("Temp: {:.1f} C".format(celsius), 0, 52)
    oled.show()


while True:
    try:
        temp_c = sensor.temperature
        display_temp(temp_c)
    except Exception as e:
        oled.fill(0)
        oled.text("Sensor Error!", 0, 30)
        oled.show()
    
    utime.sleep(1)