保姆级教程:用树莓派4B和Python监控室内温湿度(DHT22传感器)
树莓派4B与DHT22传感器打造高精度室内温湿度监控系统1. 项目概述与硬件准备在智能家居和物联网应用蓬勃发展的今天环境监测已成为许多DIY爱好者的入门项目。树莓派4B作为一款性能强劲的单板计算机搭配DHT22高精度温湿度传感器能够构建一个稳定可靠的室内环境监测系统。相比市面上常见的智能家居产品这种DIY方案不仅成本更低还能提供更高的数据掌控权和定制灵活性。所需硬件清单树莓派4B任何内存版本均可DHT22温湿度传感器也称AM23023根杜邦线母对母可选面包板用于临时测试5V/3A电源适配器为树莓派供电DHT22传感器具有以下技术特性温度测量范围-40°C至80°C精度±0.5°C湿度测量范围0-99.9%RH精度±2%RH数字信号输出抗干扰能力强低功耗设计适合长期运行注意市场上常见的DHT11传感器价格更低但精度较差温度±2°C湿度±5%RH如需更高测量精度建议选择DHT22。2. 硬件连接与系统配置2.1 物理连接指南DHT22传感器通常有三个引脚部分型号可能有四个引脚其中一个是空脚VCC电源正极连接树莓派的3.3V引脚物理引脚1DATA数据线连接GPIO4物理引脚7GND地线连接任意GND引脚如物理引脚9树莓派GPIO引脚示意图 3.3V [1] o---o [2] 5V GPIO2/SDA [3] o---o [4] 5V GPIO3/SCL [5] o---o [6] GND GPIO4 [7] o---o [8] GPIO14/TXD GND [9] o---o [10] GPIO15/RXD2.2 系统环境准备首先确保树莓派系统是最新版Raspberry Pi OS原Raspbian。打开终端执行以下命令更新系统sudo apt update sudo apt full-upgrade -y安装必要的Python开发工具和GPIO库sudo apt install python3-dev python3-pip sudo pip3 install --upgrade setuptools3. 软件实现与数据采集3.1 Python环境配置我们将使用Adafruit提供的DHT库来读取传感器数据。虽然可以直接从GitHub克隆原始库但更推荐使用维护更活跃的CircuitPython版本sudo pip3 install adafruit-circuitpython-dht sudo apt install libgpiod23.2 基础数据读取脚本创建一个名为dht22_monitor.py的文件内容如下import time import adafruit_dht import board # 初始化传感器使用GPIO4 dht_device adafruit_dht.DHT22(board.D4) def read_sensor(): try: temperature dht_device.temperature humidity dht_device.humidity return temperature, humidity except RuntimeError as error: print(error.args[0]) return None, None except Exception as error: dht_device.exit() raise error while True: temp, humidity read_sensor() if temp is not None and humidity is not None: print(f温度: {temp:.1f}°C, 湿度: {humidity:.1f}%) else: print(读取失败稍后重试...) time.sleep(2.0)运行脚本python3 dht22_monitor.py4. 系统优化与高级功能4.1 提高读取稳定性DHT22传感器对时序要求严格在树莓派上可能会遇到读取失败的情况。以下是几种改进方法添加硬件上拉电阻在DATA线和3.3V之间连接一个4.7kΩ-10kΩ的电阻优化读取间隔DHT22两次读取间隔建议不小于2秒异常处理如上面代码所示完善的异常处理能防止程序崩溃4.2 数据持久化存储将监测数据保存到CSV文件中便于后续分析import csv from datetime import datetime def save_to_csv(temp, humidity): with open(environment_data.csv, a, newline) as file: writer csv.writer(file) writer.writerow([ datetime.now().strftime(%Y-%m-%d %H:%M:%S), round(temp, 1), round(humidity, 1) ])在读取成功的条件分支中调用此函数if temp is not None and humidity is not None: print(f温度: {temp:.1f}°C, 湿度: {humidity:.1f}%) save_to_csv(temp, humidity)4.3 设置开机自启动为了让监控系统在树莓派启动时自动运行我们可以创建一个systemd服务创建服务文件/etc/systemd/system/dht22.service[Unit] DescriptionDHT22 Environmental Monitor Afternetwork.target [Service] ExecStart/usr/bin/python3 /home/pi/dht22_monitor.py WorkingDirectory/home/pi StandardOutputinherit StandardErrorinherit Restartalways Userpi [Install] WantedBymulti-user.target启用并启动服务sudo systemctl daemon-reload sudo systemctl enable dht22.service sudo systemctl start dht22.service5. 数据可视化与远程访问5.1 实时数据可视化使用Matplotlib创建简单的趋势图import matplotlib.pyplot as plt import pandas as pd from matplotlib.dates import DateFormatter def plot_data(): data pd.read_csv(environment_data.csv, names[timestamp, temperature, humidity], parse_dates[timestamp]) fig, (ax1, ax2) plt.subplots(2, 1, figsize(10, 6)) ax1.plot(data[timestamp], data[temperature], r-) ax1.set_ylabel(温度 (°C)) ax1.grid(True) ax2.plot(data[timestamp], data[humidity], b-) ax2.set_ylabel(湿度 (%)) ax2.grid(True) ax1.xaxis.set_major_formatter(DateFormatter(%m-%d %H:%M)) ax2.xaxis.set_major_formatter(DateFormatter(%m-%d %H:%M)) plt.tight_layout() plt.savefig(environment_plot.png) plt.close()5.2 搭建简易Web界面使用Flask创建一个简单的Web服务来查看实时数据from flask import Flask, render_template_string import threading app Flask(__name__) latest_data {temperature: None, humidity: None} app.route(/) def dashboard(): return render_template_string( h1环境监测仪表板/h1 p当前温度: {{ temp }}°C/p p当前湿度: {{ hum }}%/p img src/plot alt趋势图 , templatest_data[temperature], humlatest_data[humidity]) app.route(/plot) def show_plot(): return send_file(environment_plot.png, mimetypeimage/png) def run_flask(): app.run(host0.0.0.0, port8080) # 在主线程中启动Flask flask_thread threading.Thread(targetrun_flask) flask_thread.daemon True flask_thread.start()记得在主循环中更新latest_data变量if temp is not None and humidity is not None: latest_data[temperature] temp latest_data[humidity] humidity