2026/3/25 16:26:50
网站建设
项目流程
怀化网站定制,北京建设网站公司网站,thinkphp和wordpress,个人在线网站推广文章目录摘要1. 系统架构设计2. 开发环境搭建2.1 系统要求2.2 安装依赖库3. 硬件连接传感器接线图4. 核心代码实现4.1 数据采集模块 (sensor_reader.py)4.2 数据存储引擎 (data_storage.py)4.3 实时可视化 (visualization.py)5. 系统部署流程6. 常见问题解决7. 完整技术图谱摘要…文章目录摘要1. 系统架构设计2. 开发环境搭建2.1 系统要求2.2 安装依赖库3. 硬件连接传感器接线图4. 核心代码实现4.1 数据采集模块 (sensor_reader.py)4.2 数据存储引擎 (data_storage.py)4.3 实时可视化 (visualization.py)5. 系统部署流程6. 常见问题解决7. 完整技术图谱摘要本教程详细讲解如何基于Python在Linux平台开发环境监测应用涵盖传感器数据采集、实时处理、可视化展示等全流程帮助开发者快速构建嵌入式环境监测系统。1. 系统架构设计GPIODHT11温湿度传感器Raspberry PiData AcquisitionData ProcessingSQLite DatabaseReal-time VisualizationWeb DashboardAlert SystemEmail/SMS2. 开发环境搭建2.1 系统要求Linux发行版Raspberry Pi OSPython版本3.8硬件Raspberry Pi 4B DHT11传感器2.2 安装依赖库# 安装必要驱动和库sudoapt-getinstallpython3-dev python3-pipsudopip3installAdafruit_DHT matplotlib pandas numpy smtplib3. 硬件连接传感器接线图DHT11 Raspberry Pi VCC → 3.3V (Pin 1) DATA → GPIO4 (Pin 7) GND → GND (Pin 9)4. 核心代码实现4.1 数据采集模块 (sensor_reader.py)importAdafruit_DHTimporttimeimportjsonclassSensorReader:def__init__(self,sensor_typeAdafruit_DHT.DHT11,pin4):self.sensorsensor_type self.pinpin self.data_history[]defread_data(self):humidity,temperatureAdafruit_DHT.read_retry(self.sensor,self.pin)ifhumidityisnotNoneandtemperatureisnotNone:timestamptime.strftime(%Y-%m-%d %H:%M:%S)data{timestamp:timestamp,temperature:round(temperature,1),humidity:round(humidity,1)}self.data_history.append(data)returndatareturnNone# 测试代码if__name____main__:readerSensorReader()for_inrange(3):print(reader.read_data())time.sleep(2)4.2 数据存储引擎 (data_storage.py)importsqlite3fromdatetimeimportdatetimeclassDataStorage:def__init__(self,db_pathenvironment.db):self.connsqlite3.connect(db_path)self._create_table()def_create_table(self):cursorself.conn.cursor()cursor.execute( CREATE TABLE IF NOT EXISTS sensor_data ( id INTEGER PRIMARY KEY, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, temperature REAL NOT NULL, humidity REAL NOT NULL ) )self.conn.commit()definsert_data(self,temperature,humidity):cursorself.conn.cursor()cursor.execute( INSERT INTO sensor_data (timestamp, temperature, humidity) VALUES (datetime(now), ?, ?) ,(temperature,humidity))self.conn.commit()defget_last_24h(self):cursorself.conn.cursor()cursor.execute( SELECT timestamp, temperature, humidity FROM sensor_data WHERE timestamp datetime(now, -1 day) )returncursor.fetchall()# 示例用法if__name____main__:storageDataStorage()storage.insert_data(25.3,45.2)print(storage.get_last_24h())4.3 实时可视化 (visualization.py)importmatplotlib.pyplotaspltimportmatplotlib.animationasanimationfromdata_storageimportDataStorage plt.style.use(dark_background)classLivePlotter:def__init__(self,storage):self.storagestorage self.fig,(self.ax1,self.ax2)plt.subplots(2,figsize(10,8))self.fig.suptitle(环境监测实时数据,fontsize16)defupdate_plot(self,frame):dataself.storage.get_last_24h()timestamps[row[0]forrowindata]temps[row[1]forrowindata]humids[row[2]forrowindata]self.ax1.clear()self.ax2.clear()# 温度图表self.ax1.plot(timestamps,temps,r-o,linewidth2)self.ax1.set_ylabel(温度 (°C),colorwhite)self.ax1.tick_params(axisy,labelcolorwhite)self.ax1.set_title(温度变化趋势)# 湿度图表self.ax2.plot(timestamps,humids,b-s,linewidth2)self.ax2.set_ylabel(湿度 (%),colorwhite)self.ax2.tick_params(axisy,labelcolorwhite)self.ax2.set_title(湿度变化趋势)# 格式化X轴foraxin[self.ax1,self.ax2]:ax.tick_params(axisx,rotation45)ax.grid(True,linestyle--,alpha0.6)plt.tight_layout()defstart(self):anianimation.FuncAnimation(self.fig,self.update_plot,interval10000# 10秒更新一次)plt.show()# 启动可视化if__name____main__:storageDataStorage()plotterLivePlotter(storage)plotter.start()5. 系统部署流程硬件组装系统烧录依赖安装代码部署服务配置启动监测6. 常见问题解决问题现象原因分析解决方案读取传感器返回None接触不良或电压不足检查接线并确保使用3.3V供电数据库写入失败权限问题使用chmod 777 environment.db修改权限图表显示乱码缺少中文字体安装中文字体包sudo apt install fonts-wqy-microhei7. 完整技术图谱环境监测系统操作系统LinuxRaspberry Pi OS编程语言Python 3.8核心库Adafruit_DHTMatplotlibSQLite3数据流采集层GPIO控制传感器协议解析处理层数据清洗异常检测存储层SQLite数据库CSV备份展示层实时图表Web API扩展功能邮件告警移动端监控历史数据分析