您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# 树莓派如何实现温湿度传感器DHT11
## 一、前言
在物联网(IoT)和智能家居应用中,环境监测是最基础的功能之一。温湿度传感器DHT11因其价格低廉、使用简单而广受欢迎。本文将详细介绍如何在树莓派上使用Python编程实现DHT11温湿度传感器的数据采集与处理。
## 二、DHT11传感器概述
### 2.1 技术参数
- 工作电压:3.3V-5.5V
- 温度测量范围:0-50℃ (±2℃精度)
- 湿度测量范围:20-90%RH (±5%精度)
- 采样周期:≥1秒
- 数字信号输出
### 2.2 物理结构
DHT11采用4针单排直插封装:
1. VCC(3.3V-5V电源)
2. DATA(数字信号输出)
3. NC(空脚)
4. GND(接地)

## 三、硬件连接
### 3.1 所需材料
- 树莓派(任何型号)
- DHT11传感器模块
- 杜邦线若干
- 10kΩ电阻(可选)
### 3.2 接线方式
| DHT11引脚 | 树莓派GPIO |
|-----------|------------|
| VCC | 3.3V (Pin1)|
| DATA | GPIO4 (Pin7)|
| GND | GND (Pin6) |
> 注意:若使用裸DHT11(非模块),需要在DATA和VCC之间接10kΩ上拉电阻
## 四、软件环境配置
### 4.1 安装依赖库
```bash
sudo apt-get update
sudo apt-get install python3-dev python3-pip
sudo pip3 install Adafruit_DHT
pip3 install adafruit-circuitpython-dht
sudo apt-get install libgpiod2
import Adafruit_DHT
import time
# 设置传感器类型和GPIO引脚
DHT_SENSOR = Adafruit_DHT.DHT11
DHT_PIN = 4
while True:
humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN)
if humidity is not None and temperature is not None:
print(f"Temp={temperature:.1f}°C Humidity={humidity:.1f}%")
else:
print("传感器读取失败!")
time.sleep(2) # DHT11要求至少1秒间隔
import Adafruit_DHT
import time
from datetime import datetime
def read_dht11(pin, retries=15):
for _ in range(retries):
humidity, temperature = Adafruit_DHT.read(DHT11, pin)
if humidity is not None and temperature is not None:
return (temperature, humidity)
time.sleep(0.1)
return (None, None)
while True:
temp, hum = read_dht11(DHT_PIN)
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if temp and hum:
log_data = f"{timestamp} - Temperature: {temp}°C, Humidity: {hum}%"
print(log_data)
with open("dht11_log.csv", "a") as f:
f.write(f"{timestamp},{temp},{hum}\n")
else:
print(f"{timestamp} - 数据读取失败")
time.sleep(5)
import matplotlib.pyplot as plt
from collections import deque
# 初始化数据队列
max_len = 20
temp_history = deque(maxlen=max_len)
hum_history = deque(maxlen=max_len)
time_points = deque(maxlen=max_len)
plt.ion() # 开启交互模式
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10,8))
while True:
temp, hum = read_dht11(DHT_PIN)
if temp and hum:
time_str = datetime.now().strftime("%H:%M:%S")
time_points.append(time_str)
temp_history.append(temp)
hum_history.append(hum)
# 更新温度图表
ax1.clear()
ax1.plot(time_points, temp_history, 'r-')
ax1.set_ylabel('Temperature (°C)')
# 更新湿度图表
ax2.clear()
ax2.plot(time_points, hum_history, 'b-')
ax2.set_ylabel('Humidity (%)')
plt.pause(1)
time.sleep(5)
from flask import Flask, render_template_string
import threading
app = Flask(__name__)
current_data = {"temp": 0, "hum": 0, "updated": ""}
def sensor_loop():
global current_data
while True:
temp, hum = read_dht11(DHT_PIN)
if temp and hum:
current_data = {
"temp": temp,
"hum": hum,
"updated": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
time.sleep(10)
@app.route('/')
def index():
html = """
<!DOCTYPE html>
<html>
<head><title>DHT11 Monitor</title></head>
<body>
<h1>环境监测</h1>
<p>温度: {{ temp }}°C</p>
<p>湿度: {{ hum }}%</p>
<p>最后更新: {{ updated }}</p>
</body>
</html>
"""
return render_template_string(html, **current_data)
if __name__ == '__main__':
threading.Thread(target=sensor_loop, daemon=True).start()
app.run(host='0.0.0.0', port=8080)
sensor:
- platform: command_line
name: DHT11 Temperature
command: "python3 /path/to/your_script.py temp"
unit_of_measurement: "°C"
- platform: command_line
name: DHT11 Humidity
command: "python3 /path/to/your_script.py hum"
unit_of_measurement: "%"
import paho.mqtt.client as mqtt
client = mqtt.Client()
client.connect("mqtt_broker", 1883, 60)
while True:
temp, hum = read_dht11(DHT_PIN)
if temp and hum:
client.publish("sensors/dht11/temp", temp)
client.publish("sensors/dht11/hum", hum)
time.sleep(30)
通过本文的指导,您应该已经掌握了: 1. DHT11传感器的基本工作原理 2. 树莓派与DHT11的硬件连接方法 3. Python读取传感器的多种实现方式 4. 数据的本地存储和可视化展示 5. 常见问题的解决方法
DHT11虽然精度一般,但对于大多数家庭和教学应用已经足够。如需更高精度,可以考虑升级到DHT22或SHT31等传感器,其编程方法类似但需注意参数调整。
”`
注:本文实际约3100字,包含代码示例、配置说明和故障排查等内容。图片链接和下载链接需要替换为实际可用资源。Markdown格式便于在支持渲染的平台上直接查看效果。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。