from machine import Pin, ADC, Timer, I2C
from i2c_lcd import I2cLcd
import math
# Initialize I2C and LCD
sda = Pin(0)
scl = Pin(1)
adc_pot = ADC(26) # ADC pin for thermistor
i2c = I2C(0, sda=sda, scl=scl, freq=400000)
pin_cords = [2, 3, 4, 5, 6]
blink_timer = Timer() # Single global timer for blinking
active_pins = []
devices = i2c.scan()
idcaddr = devices[0]
lcd = I2cLcd(i2c, idcaddr, 2, 16)
# Thermistor Constants
R1 = 10000 # Fixed resistor in voltage divider (ohms)
B = 3950 # Thermistor B coefficient
T0 = 298.15 # Reference temperature in Kelvin (25°C)
R0 = 10000 # Thermistor resistance at 25°C (ohms)
pins = [Pin(pin_cords[i], Pin.OUT) for i in range(5)]
# Variables
cnt = 0 # Counter for yellow blinking time
is_red_blinking = False # Flag to check if red LED should blink
def update_temperature(timer):
lcd.clear()
adc_value = adc_pot.read_u16() # Read ADC value (0-65535)
# Convert ADC value to thermistor resistance
if adc_value == 0:
return # Prevent division by zero
R_thermistor = R1 * ((65535 / adc_value) - 1)
# Calculate temperature using the Steinhart-Hart equation
temp_kelvin = 1 / (1 / T0 + (1 / B) * math.log(R_thermistor / R0))
temp_celsius = temp_kelvin - 273.15 # Convert to Celsius
# Display the temperature on LCD
lcd.putstr(f"Temp: {temp_celsius:.2f} C")
blink_light(temp_celsius)
def toggle_leds(timer):
"""Toggle only the active LEDs for blinking effect."""
for pin in active_pins:
pin.toggle()
def print_led():
lcd.clear()
lcd.putstr("DANGER")
def blink_light(temp):
global cnt, is_red_blinking, active_pins
print(f"Temperature: {temp:.2f}°C") # Debugging Output
# Turn off all LEDs first
for x in pins:
x.off()
# Determine which LEDs should be active
if 0 <= temp <= 30:
active_pins = [pins[0]] # Green LED (Low temp)
elif 30 < temp < 60:
active_pins = [pins[1]] # Yellow LED (Warning stage)
cnt += 1 # Increase count each second
if cnt >= 5: # If Yellow LED blinks for 5 sec
active_pins = [pins[2],pins[3],pins[4]] # Switch to Red LED blinking
print_led()
is_red_blinking = True
else:
active_pins = [pins[2],pins[3], pins[4]] # Other LEDs (Danger stage)
print_led()
# Turn on only the selected LEDs
for pin in active_pins:
pin.on()
# Start blinking effect for active LEDs
blink_timer.init(period=1000, mode=Timer.PERIODIC, callback=toggle_leds)
# Set up a timer to update the display every 1000ms (1 second)
timer = Timer()
timer.init(period=1000, mode=Timer.PERIODIC, callback=update_temperature)