from machine import ADC, Pin
from math import log
import time
BETA = 3950 # Beta coefficient of the thermistor
R0 = 10000 # Resistance of thermistor at 25 degrees Celsius
T0 = 298.15 # Reference temperature (Kelvin) for Beta calculation
old_temperature = 0.0
adc = ADC(Pin(28))
pins = [
Pin(2, Pin.OUT), # A
Pin(3, Pin.OUT), # B
Pin(4, Pin.OUT), # C
Pin(5, Pin.OUT), # D
Pin(6, Pin.OUT), # E
Pin(8, Pin.OUT), # F
Pin(7, Pin.OUT), # G
Pin(0, Pin.OUT) # DP (not connected)
]
pins_2 = [
Pin(18, Pin.OUT), # A
Pin(19, Pin.OUT), # B
Pin(20, Pin.OUT), # C
Pin(21, Pin.OUT), # D
Pin(22, Pin.OUT), # E
Pin(27, Pin.OUT), # F
Pin(26, Pin.OUT), # G
Pin(0, Pin.OUT) # DP (not connected)
]
# Common anode 7-segment display digit patterns
digits = [
[0, 0, 0, 0, 0, 0, 1, 1], # 0
[1, 0, 0, 1, 1, 1, 1, 1], # 1
[0, 0, 1, 0, 0, 1, 0, 1], # 2
[0, 0, 0, 0, 1, 1, 0, 1], # 3
[1, 0, 0, 1, 1, 0, 0, 1], # 4
[0, 1, 0, 0, 1, 0, 0, 1], # 5
[0, 1, 0, 0, 0, 0, 0, 1], # 6
[0, 0, 0, 1, 1, 1, 1, 1], # 7
[0, 0, 0, 0, 0, 0, 0, 1], # 8
[0, 0, 0, 1, 1, 0, 0, 1], # 9
]
def reset():
"""Turns off all segments on the 7-segment display."""
for pin in pins:
pin.value(1)
for pin in pins_2:
pin.value(1)
def read_temperature():
analogValue = adc.read_u16()
if analogValue == 0: # Avoid division by zero
analogValue = 1
resistance = (65535 / analogValue) - 1
resistance = R0 / resistance
temperature = 1 / (log(resistance / R0) / BETA + 1.0 / T0) - 273.15
return temperature
reset()
switch = Pin(13, Pin.IN)
if __name__ == "__main__":
while True:
temperature = read_temperature()
if temperature < 0:
temperature = 0
tens = int(temperature) // 10
units = int(temperature) % 10
if temperature != old_temperature:
print("Temperature: {:.2f} ℃".format(temperature))
# Display tens digit
for i in range(len(pins)):
pins[i].value(digits[tens][i])
# Display units digit
for i in range(len(pins_2)):
pins_2[i].value(digits[units][i])
old_temperature = temperature
time.sleep(0.01)