011 - ESP32 MicroPython: DHT11, DHT22 in MicroPython

Introduction

In this tutorial, we will learn to use the DHT22 in MicroPython. DHT11 should be compatible with slight modification.

Circuit Diagram

Hardware Instruction

  1. Connect the OLED VCC pin to 3V3 supply pin of ESP32.
  2. Connect the OLED GND pin to ESP32 GND pin.
  3. Connect the OLED SCL pin to ESP32 GPIO D22 pin (SCL dedicated pin).
  4. Connect the OLED SDA pin to ESP32 GPIO D21 pin (SDA dedicated pin).
  5. Connect the DHT VCC pin to 3V3 supply pin of ESP32.
  6. Connect the DHT GND pin to ESP32 GND pin.
  7. Connect the DHT Signal pin to ESP32 GPIO D23 pin.

Video Demonstration

Call To Action

If you have any question regarding this tutorial, please do not hesitate to write your inquiry in the comment box provided.

If you enjoy this tutorial, please consider supporting me by Subscribing. Click this to Subscribe to TechToTinker Youtube channel.

Thank you.

Source Code

Example 1, Display DHT readings in OLED display:

 1
 2# Display DHT22 readings in 0.96 OLED display
 3# Date: October 1, 2020
 4
 5# Import the machine module to access the pins
 6import machine
 7# Import the time module for the intervals
 8import time
 9
10# OLED display initializations
11import ssd1306
12scl = machine.Pin(22, machine.Pin.OUT, machine.Pin.PULL_UP)
13sda = machine.Pin(21, machine.Pin.OUT, machine.Pin.PULL_UP)
14i2c = machine.I2C(scl=scl, sda=sda, freq=400000)
15oled = ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
16
17# DHT sensor initializations
18import dht
19d = dht.DHT22(machine.Pin(23))
20# If you will use DHT11, change it to:
21# d = dht.DHT11(machine.Pin(23))
22
23# Simple function for displaying the 
24# humidity and temperature readings
25# in the OLED display
26def display_reads():
27	# Get the DHT readings
28    d.measure()
29    t = d.temperature()
30    h = d.humidity()
31    
32    # Clear the screen by populating the screen with black
33    oled.fill(0)
34    # Display the temperature
35    oled.text('Temperature *C:', 10, 10)
36    oled.text(str(t), 90, 20)
37    # Display the humidity
38    oled.text('Humidity %:', 10, 40)
39    oled.text(str(h), 90, 50)
40    # Update the screen display
41    oled.show()
42    
43    # Or you may use the REPL
44    print('Temperature:', t, '*C', ' ', 'Humidity', h, '%')
45
46
47INTERVAL = 2000			# Sets the interval to 2 seconds
48start = time.ticks_ms() # Records the current time
49display_reads()			# Initial display	
50
51# This is the main loop
52while True:
53	# This if statements will be true every
54    # INTERVAL milliseconds, for this example,
55    # it will trigger every 2 seconds since 
56    # DHT22 samples every 2 seconds interval
57    if time.ticks_ms() - start >= INTERVAL:
58    	# Update the display
59        display_reads()		
60        # Record the new start time
61        start = time.ticks_ms()


Posts in this series



No comments yet!

GitHub-flavored Markdown & a sane subset of HTML is supported.