{"id":795,"date":"2018-06-30T17:18:23","date_gmt":"2018-07-01T00:18:23","guid":{"rendered":"http:\/\/cywang.no-ip.org\/wordpress\/?p=795"},"modified":"2018-06-30T17:19:29","modified_gmt":"2018-07-01T00:19:29","slug":"raspberry-pi-measure-temperature-and-humidity-using-dht11","status":"publish","type":"post","link":"http:\/\/cywang.no-ip.org\/wordpress\/?p=795","title":{"rendered":"Raspberry Pi &#8211; Measure Temperature and Humidity using DHT11"},"content":{"rendered":"<p><strong>Hardware components:<\/strong><\/p>\n<ul>\n<li>Raspberry Pi 3<\/li>\n<li>DHT11 Temperature and Humidity Sensor [1] (I use DHT11 because this is what I have now. Also, it&#8217;s good enough for my environment &#8211; 0 ~ 40 degrees Celsius.)<\/li>\n<\/ul>\n<p><!--more--><\/p>\n<p style=\"padding-left: 30px;\"><a href=\"http:\/\/cywang.no-ip.org\/wordpress\/wp-content\/uploads\/2018\/06\/DHT11_PIN.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-796\" src=\"http:\/\/cywang.no-ip.org\/wordpress\/wp-content\/uploads\/2018\/06\/DHT11_PIN.png\" alt=\"\" width=\"205\" height=\"293\" \/><\/a><\/p>\n<p style=\"padding-left: 30px;\">Pin 1: Output<br \/>\nPin 2: VCC<br \/>\nPin 3: GND<\/p>\n<ul>\n<li>SainSmart LCD Module For Arduino 20 X 4 [2]<\/li>\n<\/ul>\n<p style=\"padding-left: 30px;\">Pin 1 : GND<br \/>\nPin 2 : 5V<br \/>\nPin 3 : Contrast (0-5V)<br \/>\nPin 4 : RS (Register Select)<br \/>\nPin 5 : R\/W (Read Write)<br \/>\nPin 6 : Enable or Strobe<br \/>\nPin 7 : Data Bit 0<br \/>\nPin 8 : Data Bit 1<br \/>\nPin 9 : Data Bit 2<br \/>\nPin 10: Data Bit 3<br \/>\nPin 11: Data Bit 4<br \/>\nPin 12: Data Bit 5<br \/>\nPin 13: Data Bit 6<br \/>\nPin 14: Data Bit 7<br \/>\nPin 15: LCD Backlight +5V**<br \/>\nPin 16: LCD Backlight GND<\/p>\n<p>&nbsp;<\/p>\n<p>Reference site:<br \/>\n<a href=\"https:\/\/www.hackster.io\/porrey\/dht11-dht22-temperature-sensor-077790\">https:\/\/www.hackster.io\/porrey\/dht11-dht22-temperature-sensor-077790<br \/>\n<\/a><\/p>\n<p><a href=\"http:\/\/www.circuitbasics.com\/how-to-set-up-the-dht11-humidity-sensor-on-the-raspberry-pi\/\">http:\/\/www.circuitbasics.com\/how-to-set-up-the-dht11-humidity-sensor-on-the-raspberry-pi\/<\/a><\/p>\n<p><a href=\"http:\/\/cywang.no-ip.org\/wordpress\/wp-content\/uploads\/2018\/06\/DHT11.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-797\" src=\"http:\/\/cywang.no-ip.org\/wordpress\/wp-content\/uploads\/2018\/06\/DHT11.png\" alt=\"\" width=\"558\" height=\"729\" srcset=\"http:\/\/cywang.no-ip.org\/wordpress\/wp-content\/uploads\/2018\/06\/DHT11.png 558w, http:\/\/cywang.no-ip.org\/wordpress\/wp-content\/uploads\/2018\/06\/DHT11-230x300.png 230w\" sizes=\"auto, (max-width: 558px) 100vw, 558px\" \/><\/a><\/p>\n<p><a href=\"http:\/\/cywang.no-ip.org\/wordpress\/wp-content\/uploads\/2018\/06\/raspberry_pi_lcd.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-large wp-image-799\" src=\"http:\/\/cywang.no-ip.org\/wordpress\/wp-content\/uploads\/2018\/06\/raspberry_pi_lcd-768x1024.jpg\" alt=\"\" width=\"584\" height=\"779\" srcset=\"http:\/\/cywang.no-ip.org\/wordpress\/wp-content\/uploads\/2018\/06\/raspberry_pi_lcd-768x1024.jpg 768w, http:\/\/cywang.no-ip.org\/wordpress\/wp-content\/uploads\/2018\/06\/raspberry_pi_lcd-225x300.jpg 225w, http:\/\/cywang.no-ip.org\/wordpress\/wp-content\/uploads\/2018\/06\/raspberry_pi_lcd.jpg 1210w\" sizes=\"auto, (max-width: 584px) 100vw, 584px\" \/><\/a><\/p>\n<p>Code:<br \/>\n(Reference: [3])<\/p>\n<pre class=\"line-numbers\"><code class=\"language-python\">#!\/usr\/bin\/python\r\n\r\nimport RPi.GPIO as GPIO\r\nimport time\r\nimport socket\r\nimport fcntl\r\nimport struct\r\nimport logging\r\nimport Adafruit_DHT\r\n\r\n# Define GPIO to LCD mapping\r\nLCD_RS = 7\r\nLCD_E  = 8\r\nLCD_D4 = 25\r\nLCD_D5 = 24\r\nLCD_D6 = 23\r\nLCD_D7 = 18\r\nLED_ON = 15\r\n \r\n# Define some device constants\r\nLCD_WIDTH = 20    # Maximum characters per line\r\nLCD_CHR = True\r\nLCD_CMD = False\r\n \r\nLCD_LINE_1 = 0x80 # LCD RAM address for the 1st line\r\nLCD_LINE_2 = 0xC0 # LCD RAM address for the 2nd line\r\nLCD_LINE_3 = 0x94 # LCD RAM address for the 3rd line\r\nLCD_LINE_4 = 0xD4 # LCD RAM address for the 4th line\r\n \r\n# Timing constants\r\nE_PULSE = 0.0005\r\nE_DELAY = 0.0005\r\n \r\ndef main():\r\n  # Main program block\r\n  logging.basicConfig(filename='\/home\/cywang\/sensor.log', format='%(asctime)s %(message)s', level=logging.DEBUG, datefmt='%Y.%m.%d %I:%M:%S')\r\n\r\n  logging.debug(\"Start temperature and humidity monitor\")\r\n \r\n  GPIO.setmode(GPIO.BCM)       # Use BCM GPIO numbers\r\n  GPIO.setup(LCD_E, GPIO.OUT)  # E\r\n  GPIO.setup(LCD_RS, GPIO.OUT) # RS\r\n  GPIO.setup(LCD_D4, GPIO.OUT) # DB4\r\n  GPIO.setup(LCD_D5, GPIO.OUT) # DB5\r\n  GPIO.setup(LCD_D6, GPIO.OUT) # DB6\r\n  GPIO.setup(LCD_D7, GPIO.OUT) # DB7\r\n\r\n \r\n  # Initialise display\r\n  logging.debug(\"Initialize LCD\")\r\n  lcd_init()\r\n \r\n\r\n  logging.debug(\"Retrieving IP address\")\r\n  hasIp = False\r\n  retry = 3\r\n  while hasIp != True and retry &gt; 0:\r\n    lanIp = get_ip_address('enxb827eb936cc3')\r\n    wirelessIp = get_ip_address('wlan0')\r\n    if lanIp != 'N\/A':\r\n      lcd_string(\"LAN IP\",LCD_LINE_1,1)\r\n      lcd_string(lanIp,LCD_LINE_2,1)\r\n      hasIp = True\r\n    elif wirelessIp != 'N\/A':\r\n      lcd_string(\"Wireless IP\",LCD_LINE_1,1)\r\n      lcd_string(wirelessIp,LCD_LINE_2,1)\r\n      hasIp = True\r\n    else:\r\n      lcd_string(\"IP Address\",LCD_LINE_1,1)\r\n      lcd_string(\"    N'A\" ,LCD_LINE_2,1)\r\n      retry = retry - 1\r\n      logging.debug('Retry time: {0:d}'.format(3 - retry))\r\n      time.sleep(60) \r\n\r\n  logging.debug(\"Monitoring temperature and humidity...\")\r\n  lcd_string(\"Temperature\/Humidity\",LCD_LINE_3,1)\r\n  while True:\r\n    sensor_data = get_temperature_and_humidity()\r\n    lcd_string(sensor_data,LCD_LINE_4,1)\r\n    #logging.debug(sensor_data)\r\n    #print sensor_data\r\n    time.sleep(10) \r\n\r\ndef get_temperature_and_humidity():\r\n  sensor = Adafruit_DHT.DHT11\r\n  pin = 4\r\n\r\n  try:\r\n    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)\r\n    if humidity is not None and temperature is not None:\r\n      deg = u'\\xb0'\r\n      logging.debug('Temperature: {0:0.1f} {1:s}C - Humidity: {2:0.1f}%'.format(temperature, deg.encode('utf8'), humidity))\r\n      return '{0:0.1f} C \/ {1:0.1f}%'.format(temperature, humidity)\r\n    else:\r\n      return \"Failed to get temperature\/humidity\"\r\n  except:\r\n      return \"Failed to get temperature\/humidity\"\r\n\r\ndef get_ip_address(ifname):\r\n  try:\r\n    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n    return socket.inet_ntoa(fcntl.ioctl(\r\n      s.fileno(),\r\n      0x8915,  # SIOCGIFADDR\r\n      struct.pack('256s', ifname[:15])\r\n    )[20:24])\r\n  except:\r\n    return \"N\/A\"\r\n \r\ndef lcd_init():\r\n  # Initialise display\r\n  lcd_byte(0x33,LCD_CMD) # 110011 Initialise\r\n  lcd_byte(0x32,LCD_CMD) # 110010 Initialise\r\n  lcd_byte(0x06,LCD_CMD) # 000110 Cursor move direction\r\n  lcd_byte(0x0C,LCD_CMD) # 001100 Display On,Cursor Off, Blink Off\r\n  lcd_byte(0x28,LCD_CMD) # 101000 Data length, number of lines, font size\r\n  lcd_byte(0x01,LCD_CMD) # 000001 Clear display\r\n  time.sleep(E_DELAY)\r\n \r\ndef lcd_byte(bits, mode):\r\n  # Send byte to data pins\r\n  # bits = data\r\n  # mode = True  for character\r\n  #        False for command\r\n \r\n  GPIO.output(LCD_RS, mode) # RS\r\n \r\n  # High bits\r\n  GPIO.output(LCD_D4, False)\r\n  GPIO.output(LCD_D5, False)\r\n  GPIO.output(LCD_D6, False)\r\n  GPIO.output(LCD_D7, False)\r\n  if bits&amp;0x10==0x10:\r\n    GPIO.output(LCD_D4, True)\r\n  if bits&amp;0x20==0x20:\r\n    GPIO.output(LCD_D5, True)\r\n  if bits&amp;0x40==0x40:\r\n    GPIO.output(LCD_D6, True)\r\n  if bits&amp;0x80==0x80:\r\n    GPIO.output(LCD_D7, True)\r\n \r\n  # Toggle 'Enable' pin\r\n  lcd_toggle_enable()\r\n \r\n  # Low bits\r\n  GPIO.output(LCD_D4, False)\r\n  GPIO.output(LCD_D5, False)\r\n  GPIO.output(LCD_D6, False)\r\n  GPIO.output(LCD_D7, False)\r\n  if bits&amp;0x01==0x01:\r\n    GPIO.output(LCD_D4, True)\r\n  if bits&amp;0x02==0x02:\r\n    GPIO.output(LCD_D5, True)\r\n  if bits&amp;0x04==0x04:\r\n    GPIO.output(LCD_D6, True)\r\n  if bits&amp;0x08==0x08:\r\n    GPIO.output(LCD_D7, True)\r\n \r\n  # Toggle 'Enable' pin\r\n  lcd_toggle_enable()\r\n \r\ndef lcd_toggle_enable():\r\n  # Toggle enable\r\n  time.sleep(E_DELAY)\r\n  GPIO.output(LCD_E, True)\r\n  time.sleep(E_PULSE)\r\n  GPIO.output(LCD_E, False)\r\n  time.sleep(E_DELAY)\r\n \r\ndef lcd_string(message,line,style):\r\n\r\n  if style==1:\r\n    message = message.ljust(LCD_WIDTH,\" \")\r\n  elif style==2:\r\n    message = message.center(LCD_WIDTH,\" \")\r\n  elif style==3:\r\n    message = message.rjust(LCD_WIDTH,\" \")\r\n \r\n  lcd_byte(line, LCD_CMD)\r\n \r\n  for i in range(LCD_WIDTH):\r\n    lcd_byte(ord(message[i]),LCD_CHR)\r\n \r\ndef lcd_backlight(flag):\r\n  GPIO.output(LED_ON, flag)\r\n \r\nif __name__ == '__main__':\r\n  main()\r\n  logging.debug(\"Exit\")<\/code><\/pre>\n<p>&nbsp;<\/p>\n<p>[1] Elegoo EL-KIT-000 37-in-1 Sensor Module Kit: <a href=\"https:\/\/www.amazon.com\/Elegoo-EL-KIT-000-Sensor-Module-Arduino\/dp\/B009OVGKTQ\/ref=pd_rhf_gw_p_img_1?_encoding=UTF8&amp;psc=1&amp;refRID=W72V8TDE9K93Z2ZYVXMG\">Amazon Link<\/a><\/p>\n<p>[2] SainSmart LCD Module For Arduino 20 X 4: <a href=\"https:\/\/www.amazon.com\/gp\/product\/B003B22UR0\/ref=oh_aui_search_detailpage?ie=UTF8&amp;psc=1\">Amazon Link<\/a><\/p>\n<p>[3] <a href=\"https:\/\/github.com\/brantje\/rpi-16x2-lcd\/blob\/master\/lcd.py\">https:\/\/github.com\/brantje\/rpi-16&#215;2-lcd\/blob\/master\/lcd.py<\/a><\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hardware components: Raspberry Pi 3 DHT11 Temperature and Humidity Sensor [1] (I use DHT11 because this is what I have now. Also, it&#8217;s good enough for my environment &#8211; 0 ~ 40 degrees Celsius.)<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_exactmetrics_skip_tracking":false,"_exactmetrics_sitenote_active":false,"_exactmetrics_sitenote_note":"","_exactmetrics_sitenote_category":0,"footnotes":""},"categories":[25,1],"tags":[],"class_list":["post-795","post","type-post","status-publish","format-standard","hentry","category-raspberry-pi","category-uncategorized"],"_links":{"self":[{"href":"http:\/\/cywang.no-ip.org\/wordpress\/index.php?rest_route=\/wp\/v2\/posts\/795","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/cywang.no-ip.org\/wordpress\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/cywang.no-ip.org\/wordpress\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/cywang.no-ip.org\/wordpress\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/cywang.no-ip.org\/wordpress\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=795"}],"version-history":[{"count":4,"href":"http:\/\/cywang.no-ip.org\/wordpress\/index.php?rest_route=\/wp\/v2\/posts\/795\/revisions"}],"predecessor-version":[{"id":802,"href":"http:\/\/cywang.no-ip.org\/wordpress\/index.php?rest_route=\/wp\/v2\/posts\/795\/revisions\/802"}],"wp:attachment":[{"href":"http:\/\/cywang.no-ip.org\/wordpress\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=795"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/cywang.no-ip.org\/wordpress\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=795"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/cywang.no-ip.org\/wordpress\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=795"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}