from machine import Pin, I2C
import onewire, ds18x20, time
# ---------------- I2C LCD Setup ----------------
i2c = I2C(1, scl=Pin(3), sda=Pin(2), freq=400000)
LCD_ADDR = 0x27 # common I2C LCD address
def lcd_write_cmd(cmd):
high = cmd & 0xF0
low = (cmd << 4) & 0xF0
for nib in [high, low]:
i2c.writeto(LCD_ADDR, bytes([nib | 0x04 | 0x08]))
i2c.writeto(LCD_ADDR, bytes([nib | 0x08]))
def lcd_write_char(ch):
high = ch & 0xF0
low = (ch << 4) & 0xF0
for nib in [high, low]:
i2c.writeto(LCD_ADDR, bytes([nib | 0x04 | 0x09]))
i2c.writeto(LCD_ADDR, bytes([nib | 0x09]))
def lcd_init():
time.sleep_ms(20)
lcd_write_cmd(0x28) # 4-bit, 2-line
lcd_write_cmd(0x0C) # Display on
lcd_write_cmd(0x01) # Clear
lcd_write_cmd(0x06) # Entry mode
lcd_write_cmd(0x80) # Move cursor to first line
def lcd_print(text):
for c in text:
lcd_write_char(ord(c))
# ---------------- DS18B20 Setup ----------------
ds_pin = Pin(14)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(Pin(14)))
time.sleep_ms(500) # Give sensor time to power up
roms = ds_sensor.scan()
if not roms:
print("No DS18B20 sensor found!")
while True:
pass
# ---------------- Main Loop ----------------
lcd_init()
lcd_write_cmd(0x80) # Line 1
lcd_print("Hello") # Display Hello on first line
while True:
ds_sensor.convert_temp()
time.sleep_ms(750) # Wait for conversion
temp = ds_sensor.read_temp(roms[0])
lcd_write_cmd(0xC0) # Line 2
# Temperature ranges and messages
if temp < 37.5:
message = "Low Urgency"
elif 37.5 <= temp < 39.0:
message = "Priority"
else:
message = "Urgent"
lcd_write_cmd(0xC0) # Move cursor to line 2 again
lcd_print("T:{:.1f}C {}".format(temp, message))
time.sleep(2)