Temperature and humidity are also very common indicators in our daily lives, and I used the DHT11 digital temperature and humidity sensors on my Raspberry Pi.

This is the wiring diagram of the DHT11 on the PiHAT, and we can see that the DHT11 is connected to pin 19 of the Raspberry PI, which can be programmed to drive the DHT11 sensor. Different sensors have different libraries, for the DHT11 we can use the Adafruit_DHT library to control it.

The installation instructions are as follows: type this command into the terminal in Raspberry Pi
sudo pip3 install Adafruit_DHT
Functions to Control DHT11
sensor=Adafruit_DHT.DHT11 # sensor= Adafruit_DHT.SENSOR: where SENSOR is the specified sensor type which in my occasion is DHT11, it could be either DHT11, DTH22, or AM2302. It tells the Pi which sensor I am using.
# How to use the function:
humidity, temperature Adafruit_DHT.read_retry(sensor, pin) # This line of code returns the temperature and humidity information as a float datatype.
Flowchart

Code
Here’s how it is achieved:
#import all necessary module
import Adafruit_DHT, time
from luma.core.render import canvas
from luma.oled.device import ssd1306
#initialize both the OLED and DHT11 temperature sensor
device = ssd1306(port=1, address=0x3C)
sensor = Adafruit_DHT.DHT11
#the sensor is connected to pin 19, so it is set to the variable gpio
gpio = 19
while True:
humidity, temperature = Adafruit_DHT.read_retry(sensor, gpio)
# In order to avoid occasional read failure, it first determine whether the read is successful, and then print the relevant data
if humidity is not None and temperature is not None:
with canvas(device) as draw:
draw.text((0, 0), 'Rich Designed', fill="white")
draw.text((0, 15), 'DHT11 test:', fill="white")
draw.text((0, 40), '%.1f'%temperature+' C'+' '+'%.1f'%humidity+' %', fill="White")
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))
else:
with canvas(device) as draw:
draw.text((0, 0), 'Rich Designed', fill="white")
draw.text((0, 15), 'DHT11 test:', fill="white")
draw.text((0, 40), 'Failed to read!', fill="white")
print('Failed to get reading. Try again!')
time.sleep(2)
Result
Humidity Sensor