from machine import Pin, I2C
import time
import dht
from pico_i2c_lcd import I2cLcd
# Initialize DHT11
dht11 = dht.DHT11(Pin(15))
# Initialize I2C for LCD
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
I2C_ADDR = 0x27
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)
while True:
try:
dht11.measure()
temp = dht11.temperature()
humidity = dht11.humidity()
# Display the readings on LCD
lcd.clear()
lcd.putstr("Temp: {}C".format(temp))
lcd.move_to(0, 1)
lcd.putstr("Humidity: {}%".format(humidity))
# Print to console
print("Temperature: {}C".format(temp))
print("Humidity: {}%".format(humidity))
except OSError as e:
print('Failed to read sensor.')
time.sleep(2)
# pico_i2c_lcd.py
import utime
from machine import I2C
class I2cLcd:
# LCD Commands
LCD_CLR = 0x01
LCD_HOME = 0x02
def __init__(self, i2c, address, num_lines, num_columns):
self.i2c = i2c
self.address = address
self.num_lines = num_lines
self.num_columns = num_columns
self.init_lcd()
def init_lcd(self):
utime.sleep_ms(20)
self.i2c.writeto(self.address, b'\x03')
utime.sleep_ms(5)
self.i2c.writeto(self.address, b'\x03')
utime.sleep_ms(5)
self.i2c.writeto(self.address, b'\x03')
utime.sleep_ms(1)
self.i2c.writeto(self.address, b'\x02')
utime.sleep_ms(1)
self.send_command(0x28)
self.send_command(0x0C)
self.send_command(0x06)
self.send_command(self.LCD_CLR)
utime.sleep_ms(5)
def send_command(self, cmd):
self.i2c.writeto(self.address, bytes([cmd & 0xF0 | 0x08]))
self.i2c.writeto(self.address, bytes([(cmd << 4) & 0xF0 | 0x08]))
def send_data(self, data):
self.i2c.writeto(self.address, bytes([data & 0xF0 | 0x09]))
self.i2c.writeto(self.address, bytes([(data << 4) & 0xF0 | 0x09]))
def putstr(self, string):
for char in string:
self.send_data(ord(char))
def clear(self):
self.send_command(self.LCD_CLR)
def move_to(self, line, column):
address = 0x80 | (line << 6) + column
self.send_command(address)