树莓派GPIO接口实战用DHT11温湿度传感器打造智能家居监测系统在智能家居的浪潮中环境监测系统扮演着至关重要的角色。想象一下当你不在家时能够实时掌握家中的温湿度变化甚至根据这些数据自动调节空调或加湿器——这一切都可以通过树莓派和DHT11温湿度传感器来实现。本文将带你从零开始构建一个功能完善的智能家居环境监测系统不仅实现数据采集和本地显示还能将数据存储到数据库并通过网络远程查看。1. 硬件准备与连接1.1 认识DHT11温湿度传感器DHT11是一款经济实惠的数字温湿度复合传感器具有以下特点测量范围温度0-50℃±2℃精度湿度20-90%RH±5%精度采样率每秒1次工作电压3.3V-5V接口类型单总线数字信号输出传感器通常有三个引脚VCC红色线电源正极3.3V-5VDATA绿色线数据信号线GND黑色线电源负极1.2 树莓派GPIO接口简介树莓派的GPIO通用输入输出接口是与外部设备交互的关键。以树莓派4B为例其40针GPIO排列如下物理引脚BCM编号功能物理引脚BCM编号功能1-3.3V2-5V32GPIO24-5V53GPIO36-GND..................提示建议使用BCM编号方式引用GPIO引脚这与大多数库的默认设置一致。1.3 硬件连接步骤将DHT11的VCC引脚连接到树莓派的3.3V电源物理引脚1将GND引脚连接到任意GND引脚如物理引脚6将DATA引脚连接到GPIO25物理引脚22在DATA线和VCC之间连接一个4.7kΩ上拉电阻部分DHT11模块已内置连接完成后你的硬件系统应该如下图所示[VCC 3.3V] ---- [DHT11 VCC] | [GPIO25] ------ [DHT11 DATA] | [GND] --------- [DHT11 GND]2. 软件环境配置2.1 安装必要的Python库首先更新系统并安装Python开发环境sudo apt update sudo apt install python3-dev python3-pip接下来安装DHT传感器库。我们推荐使用Adafruit_DHT库的改进版Adafruit_CircuitPython_DHTpip3 install adafruit-circuitpython-dht sudo apt install libgpiod22.2 测试传感器连接创建一个简单的测试脚本dht_test.pyimport adafruit_dht import board import time dht adafruit_dht.DHT11(board.D25) # 使用GPIO25 try: while True: try: temperature dht.temperature humidity dht.humidity print(f温度: {temperature}°C, 湿度: {humidity}%) except RuntimeError as e: print(f读取失败: {e}) time.sleep(2) except KeyboardInterrupt: print(程序结束) dht.exit()运行脚本并观察输出python3 dht_test.py正常输出应类似于温度: 23.0°C, 湿度: 45% 温度: 23.0°C, 湿度: 45%3. 构建完整的监测系统3.1 实时数据显示界面使用matplotlib创建动态更新的温湿度曲线图import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import numpy as np # 初始化图表 fig, (ax1, ax2) plt.subplots(2, 1, figsize(10, 6)) x_data, temp_data, humi_data [], [], [] line_temp, ax1.plot([], [], r-) line_humi, ax2.plot([], [], b-) def init(): ax1.set_xlim(0, 100) ax1.set_ylim(0, 50) ax1.set_title(温度监测) ax2.set_xlim(0, 100) ax2.set_ylim(0, 100) ax2.set_title(湿度监测) return line_temp, line_humi def update(frame): try: temp dht.temperature humi dht.humidity x_data.append(frame) temp_data.append(temp) humi_data.append(humi) line_temp.set_data(x_data, temp_data) line_humi.set_data(x_data, humi_data) ax1.relim() ax1.autoscale_view() ax2.relim() ax2.autoscale_view() except RuntimeError as e: print(f读取失败: {e}) return line_temp, line_humi ani FuncAnimation(fig, update, framesrange(100), init_funcinit, blitTrue) plt.tight_layout() plt.show()3.2 数据存储与数据库集成使用SQLite数据库存储历史数据import sqlite3 from datetime import datetime def init_db(): conn sqlite3.connect(environment.db) c conn.cursor() c.execute(CREATE TABLE IF NOT EXISTS sensor_data (timestamp TEXT, temperature REAL, humidity REAL)) conn.commit() conn.close() def save_data(temp, humi): conn sqlite3.connect(environment.db) c conn.cursor() timestamp datetime.now().strftime(%Y-%m-%d %H:%M:%S) c.execute(INSERT INTO sensor_data VALUES (?, ?, ?), (timestamp, temp, humi)) conn.commit() conn.close()修改之前的测试脚本加入数据存储功能init_db() try: while True: try: temperature dht.temperature humidity dht.humidity print(f温度: {temperature}°C, 湿度: {humidity}%) save_data(temperature, humidity) except RuntimeError as e: print(f读取失败: {e}) time.sleep(300) # 每5分钟记录一次 except KeyboardInterrupt: print(程序结束) dht.exit()3.3 远程监控Web界面使用Flask创建一个简单的Web服务来显示数据from flask import Flask, render_template import sqlite3 from datetime import datetime, timedelta app Flask(__name__) app.route(/) def dashboard(): conn sqlite3.connect(environment.db) c conn.cursor() # 获取最新数据 c.execute(SELECT * FROM sensor_data ORDER BY timestamp DESC LIMIT 1) latest c.fetchone() # 获取24小时数据 twenty_four_hours_ago (datetime.now() - timedelta(hours24)).strftime(%Y-%m-%d %H:%M:%S) c.execute(SELECT * FROM sensor_data WHERE timestamp ? ORDER BY timestamp, (twenty_four_hours_ago,)) history c.fetchall() conn.close() return render_template(dashboard.html, latestlatest, historyhistory) if __name__ __main__: app.run(host0.0.0.0, port8080)创建对应的HTML模板templates/dashboard.html!DOCTYPE html html head title环境监测系统/title script srchttps://cdn.plot.ly/plotly-latest.min.js/script /head body h1当前环境状态/h1 p温度: {{ latest[1] }}°C/p p湿度: {{ latest[2] }}%/p div idchart/div script var times {{ history|map(attribute0)|list|tojson }}; var temps {{ history|map(attribute1)|list|tojson }}; var humis {{ history|map(attribute2)|list|tojson }}; var trace1 { x: times, y: temps, name: 温度, type: line }; var trace2 { x: times, y: humis, name: 湿度, yaxis: y2, type: line }; var data [trace1, trace2]; var layout { title: 24小时温湿度变化, yaxis: {title: 温度 (°C)}, yaxis2: { title: 湿度 (%), overlaying: y, side: right } }; Plotly.newPlot(chart, data, layout); /script /body /html4. 系统优化与扩展4.1 提高数据采集稳定性DHT11传感器在读取时偶尔会失败我们可以实现一个更健壮的读取函数def read_sensor(max_retries5): for _ in range(max_retries): try: temp dht.temperature humi dht.humidity if temp is not None and humi is not None: return temp, humi except RuntimeError: time.sleep(1) return None, None4.2 添加异常报警功能当温度或湿度超出设定范围时发送通知def check_thresholds(temp, humi): if temp 30: send_alert(高温警告: 当前温度 {}°C.format(temp)) if humi 30: send_alert(低湿度警告: 当前湿度 {}%.format(humi)) def send_alert(message): # 这里可以实现邮件、短信或推送通知 print(警报: message) # 示例使用curl发送HTTP请求到IFTTT # import requests # requests.post(https://maker.ifttt.com/..., data{value1:message})4.3 系统服务化为了让监测系统在后台持续运行我们可以将其设置为系统服务创建服务文件/etc/systemd/system/environment_monitor.service[Unit] DescriptionEnvironment Monitoring Service Afternetwork.target [Service] ExecStart/usr/bin/python3 /home/pi/environment_monitor.py WorkingDirectory/home/pi StandardOutputinherit StandardErrorinherit Restartalways Userpi [Install] WantedBymulti-user.target启用并启动服务sudo systemctl enable environment_monitor sudo systemctl start environment_monitor4.4 与智能家居平台集成将数据发送到Home Assistant等智能家居平台# 配置Home Assistant的REST传感器 # configuration.yaml 中添加 # sensor: # - platform: rest # name: Temperature # resource: http://树莓派IP:8080/api/temperature # unit_of_measurement: °C # - platform: rest # name: Humidity # resource: http://树莓派IP:8080/api/humidity # unit_of_measurement: % app.route(/api/temperature) def api_temp(): temp, _ read_sensor() return str(temp) app.route(/api/humidity) def api_humi(): _, humi read_sensor() return str(humi)