Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use DHT11 to read temperature and humidity on raspberry 3

Shulou Source: shulou.com Published: 2022-06-01 06:50:15 10月02日 Update

This article mainly shows you "how to read temperature and humidity with DHT11 on Raspberry 3". The content is simple and clear. I hope it can help you solve your doubts. Let me lead you to study and learn this article "how to read temperature and humidity with DHT11 on Raspberry 3".

For this example, you need to prepare the following materials:

DHT 11/22

RaspberryPI

4.7 K resistance

The specific connection method is shown in the following figure:

After connecting the line, go to the command line of raspberry to install the dependency package Adafruit_DHT that drives DHT11:

$pip install adafruit-dht

In fact, we only use one of the methods to use this package.

Humidity, temperature = Adafruit_DHT.read_retry (Adafruit_DHT.DHT11, pin)

The first parameter of the read_retry method is used to specify that the current sensor model is generally DHT11 or DHT22, and the second parameter is the connection number connected to the raspberry pie. (GPIO) this method returns a tuple (tuple) type object of a (humidity, temperature) structure.

The complete code is as follows:

Import timeimport Adafruit_DHT## Assuming the DHT11 sensor is connected to GPIO pin number 4pin = 4 def run (): while True: humidity, temperature = Adafruit_DHT.read_retry (Adafruit_DHT.DHT11, pin) if humidity is not None and temperature is not None: print "Temp= {0V f} * C Humidity= {1V f}%" .format (temperature, humidity) else: print "Failed to get reading. Try again!" # Sleep some time time.sleep (10) run ()

To run this example, you need to use sudo or it will fail.

$sudo python dht_test,.py

Use Python to do such a low-level operation although a bit awkward, but used to be good, need to pay attention to the line-by-line parsing of Python, the program will automatically exit after execution, so I will use while True in this example to simulate the main function of the lower computer in order to achieve the effect of "main loop".

This program will automatically read the temperature and humidity data on DHT every 10 seconds and print it out.

The above is all the contents of the article "how to read temperature and humidity with DHT11 on Raspberry 3". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Raspberries content articles parameters methods examples programs learning help loops running awkwardness code sensors functions slogans just commands models objects Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno vpn Shulou Information MariaDB Microsoft