[How to] connect a DHT12 I2c humidity and temperature sensor to OpenWrt and display values on LCD

If you want temperature & humidity measurements and the current time/date displayed on the I2C LCD 20x4, this is the python script you need:

note: check here for I2c LCD installation: [How To] Add 20x4 LCD (HD44780) to a OpenWrt router via I2C

vi /etc/test.py

import smbus
import I2C_LCD_driver
import time
import sys
import commands
import locale

from subprocess import check_output
from shlex import split
locale.setlocale(locale.LC_ALL, "us_US")

mylcd = I2C_LCD_driver.lcd()

mylcd.lcd_display_string(" --- OpenWrt --- ", 1)
mylcd.lcd_display_string(" I2c: DHT12 + LCD ", 2)
mylcd.lcd_display_string("by Lovisolo PM 2019", 3)
mylcd.lcd_display_string("parknat12@yahoo.com", 4)


while True:
 DEVICE     = 0x5C #device address
 bus = smbus.SMBus(0)  # Rev 2 Pi uses 1

 def readdata(addr=DEVICE):

  #read 5 bytes of data from the device address (0x05C) starting from an offset of zero
  data = bus.read_i2c_block_data(addr,0x00, 5)

  umid=("Humidity: " + str(data[0]) + "." + str(data[1]) + "%")
  temp= ("Temperature: " + str(data[2]) + "." + str(data[3]) + "C")

  #print (umid) 
  #print (temp)
  #if (data[0] + data[1] + data[2] + data[3] ==  data[4]):
  #  print "checksum is correct"
  #  print "checksum is incorrect, data error"

  mylcd.lcd_display_string(temp, 1)
  mylcd.lcd_display_string(umid, 2)
  #mylcd.lcd_display_string("put here whatever else you might need and remove comment", 3)
  mylcd.lcd_display_string("%s" %time.strftime("%a %H:%M" " " "%d/%m/%Y"), 4)

 if __name__=="__main__":

Then launch it directly from /etc/rc.local:

/usr/bin/python /etc/test.py

1 Like