释放双眼,带上耳机,听听看~!
目录
介绍
DHT11传感器
- DHT11传感器通过单根线连续测量并提供湿度和温度值。
- 它可以测量相对湿度的百分比(20至90%RH)和温度(摄氏度),范围为0至50°C。
- 它有4个引脚; 其中一个用于串行形式的数据通信。
- 不同TON和TOFF的脉冲被解码为逻辑1或逻辑0或起始脉冲或帧的结束。
电路连接图
DHT11与Raspberry Pi 3连接
例
- 在这里,我们将把DHT11传感器与Raspberry Pi 3连接,并在终端上显示湿度和温度。
- 我们将使用来自GitHub的Adafruit的DHT Sensor Python库。Adafruit Python DHT传感器库用于读取树莓派或Beaglebone Black的湿度和温度。它是为DHT系列传感器开发的,如DHT11,DHT22或AM2302。
从这里下载Adafruit DHT传感器库:
- 通过执行以下命令解压缩库并将其安装在已下载库的同一根目录中,
sudo python setup.py install
- 安装库及其依赖项后,从示例文件夹中保存的库中打开名为simpletest的示例草图。
- 在此代码中,raspberry Pi从DHT11传感器读取湿度和温度,并在终端上打印。但是,它只读取并显示一次值。所以,我们在这里改变了程序,不断打印价值。
注意:
- 将适当的传感器类型分配给此库中的传感器变量。在这里,我们使用的是DHT11传感器。
sensor = Adafruit_DHT.DHT11
- 如果有人使用传感器DHT22,那么我们需要将Adafruit_DHT.DHT22分配给上面显示的传感器变量。
- 另外,注释掉Beaglebone引脚定义并取消注释Raspberry Pi的引脚声明。
- 然后分配引脚号。DHT传感器的数据引脚连接到哪个。这里,DHT11传感器的数据连接到GPIO4。如上面的连接图所示。
Python程序
#!/usr/bin/python
# Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import Adafruit_DHT
# Sensor should be set to Adafruit_DHT.DHT11,
# Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302.
sensor = Adafruit_DHT.DHT11
# Example using a Beaglebone Black with DHT sensor
# connected to pin P8_11.
#pin = 'P8_11'
# Example using a Raspberry Pi with DHT sensor
# connected to GPIO4.
pin = 4
# Try to grab a sensor reading. Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
while True:
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))
'''
# Note that sometimes you won't get a reading and
# the results will be null (because Linux can't
# guarantee the timing of calls to read the sensor).
# If this happens try again!
if humidity is not None and temperature is not None:
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))
else:
print('Failed to get reading. Try again!')
DHT11输出
本教程完整程序下载: