# Rui Santos & Sara Santos - Random Nerd Tutorials
# Complete project details at https://RandomNerdTutorials.com/micropython-i2c-lcd-esp32-esp8266/
from machine import Pin, SoftI2C
from machine_i2c_lcd import I2cLcd
from machine import RTC
from time import sleep
import dht
import esp
esp.osdebug(None)
sensor = dht.DHT22(Pin(15))
# Define the LCD I2C address and dimensions
I2C_ADDR = 0x27
I2C_NUM_ROWS = 2
I2C_NUM_COLS = 16
# Initialize I2C and LCD objects
i2c = SoftI2C(sda=Pin(21), scl=Pin(22), freq=400000)
# for ESP8266, uncomment the following line
#i2c = SoftI2C(sda=Pin(4), scl=Pin(5), freq=400000)
lcd = I2cLcd(i2c, I2C_ADDR, I2C_NUM_ROWS, I2C_NUM_COLS)
lcd.putstr("It's working :)")
sleep(4)
def getRtcTime():
rtc=RTC()
#rtc.datetime((2024, 10, 25, 0, 12, 15, 0, 0)) # set a specific date and time
yr,mon,day,dow,hor,minute,sec,ms=rtc.datetime()
dt=(yr,mon,day,dow,hor,minute,sec,ms)
dy=dt[0];dm=dt[1];dd=dt[3];dh=dt[4];dmin=dt[5]
return(dy,dm,dd,dh,dmin)
def read_sensor():
try:
sensor.measure()
temp = str(int(sensor.temperature())) + " C"
hum = str(int(sensor.humidity())) + " %"
return temp, hum
except OSError as e:
return('Failed to read sensor.')
#print(dh,':',dmin)
#print(dd,'/',dm,'/',dy)
try:
while True:
temp, hum = read_sensor()
dy,dm,dd,dh,dmin=getRtcTime()
if 0 <= dh <= 9 and 0 <= dmin <= 9:
tstring=['0'+str(dh),'0'+str(dmin)]
elif 0 <= dmin <= 9:
tstring=[str(dh),'0'+str(dmin)]
elif 0 <= dh <= 9:
tstring=['0'+str(dh),str(dmin)]
else:
tstring=[str(dh),str(dmin)]
dstring=[str(dd),str(dm),str(dy)]
#tstring=[str(dh),str(dmin)]
date='/'.join(dstring)
time=':'.join(tstring)
#print(date)
# Clear the LCD
lcd.clear()
# Display two different messages on different lines
# By default, it will start at (0,0) if the display is empty
lcd.putstr("Temp.: " + temp)
lcd.move_to(0, 1)
lcd.putstr("Humidity: " + hum)
sleep(2)
lcd.clear()
lcd.putstr(date)
# Starting at the second line (0, 1)
lcd.move_to(0, 1)
lcd.putstr(time)
sleep(2)
except KeyboardInterrupt:
# Turn off the display
print("Keyboard interrupt")
lcd.backlight_off()
lcd.display_off()