from machine import Pin, I2C
from utime import sleep_ms
import dht
# Define DHT sensor pin
DHT_PIN = 4 # Assuming DHT sensor is connected to GPIO pin 4
# Define LCD pin numbers
LCD_RS = 12
LCD_EN = 11
LCD_D4 = 10
LCD_D5 = 9
LCD_D6 = 8
LCD_D7 = 7
# Define LCD commands
LCD_CLEAR = 0x01
LCD_RETURN_HOME = 0x02
LCD_ENTRY_MODE_SET = 0x04
LCD_DISPLAY_CONTROL = 0x08
LCD_CURSOR_SHIFT = 0x10
LCD_FUNCTION_SET = 0x20
LCD_SET_CGRAM_ADDR = 0x40
LCD_SET_DDRAM_ADDR = 0x80
# Define LCD settings
LCD_LINES = 2
LCD_WIDTH = 16
LCD_CHR = True
LCD_CMD = False
LCD_LINE_1 = 0x80
LCD_LINE_2 = 0xC0
# Initialize LCD pins
lcd_rs = Pin(LCD_RS, Pin.OUT)
lcd_en = Pin(LCD_EN, Pin.OUT)
lcd_d4 = Pin(LCD_D4, Pin.OUT)
lcd_d5 = Pin(LCD_D5, Pin.OUT)
lcd_d6 = Pin(LCD_D6, Pin.OUT)
lcd_d7 = Pin(LCD_D7, Pin.OUT)
# Function to send command/data to LCD
def lcd_byte(bits, mode):
lcd_rs.value(mode)
lcd_d4.value(bits & 0x10)
lcd_d5.value(bits & 0x20)
lcd_d6.value(bits & 0x40)
lcd_d7.value(bits & 0x80)
lcd_toggle_enable()
lcd_d4.value(bits & 0x01)
lcd_d5.value(bits & 0x02)
lcd_d6.value(bits & 0x04)
lcd_d7.value(bits & 0x08)
lcd_toggle_enable()
def lcd_toggle_enable():
lcd_en.value(True)
sleep_ms(1)
lcd_en.value(False)
sleep_ms(1)
# Function to initialize LCD
def lcd_init():
lcd_byte(0x33, LCD_CMD)
lcd_byte(0x32, LCD_CMD)
lcd_byte(LCD_FUNCTION_SET | 0x08, LCD_CMD)
lcd_byte(LCD_DISPLAY_CONTROL | 0x04, LCD_CMD)
lcd_byte(LCD_CLEAR, LCD_CMD)
sleep_ms(2)
lcd_byte(LCD_ENTRY_MODE_SET | 0x04, LCD_CMD)
lcd_byte(LCD_RETURN_HOME, LCD_CMD)
# Function to display data on LCD
def lcd_string(message, line):
if line == 1:
lcd_byte(LCD_LINE_1, LCD_CMD)
elif line == 2:
lcd_byte(LCD_LINE_2, LCD_CMD)
for char in message:
lcd_byte(ord(char), LCD_CHR)
# Initialize DHT sensor
dht_sensor = dht.DHT22(Pin(DHT_PIN))
def read_dht():
dht_sensor.measure()
temp_c = dht_sensor.temperature()
humidity = dht_sensor.humidity()
print("Temperature:", temp_c)
print("Humidity:", humidity)
return temp_c, humidity
def main():
lcd_init()
while True:
temp_c, humidity = read_dht()
lcd_string("Temp: {:.1f}C".format(temp_c), 1)
lcd_string("Humidity: {:.1f}%".format(humidity), 2)
sleep_ms(2000) # Update every 2 seconds