基于RaspberryPi的燃气传感器数据远程可视化最优简易方案咨询
简洁可行的树莓派燃气数据在线可视化方案
方案1:Google Sheets 直连(零复杂配置,自带可视化)
- 核心逻辑:借助Google Sheets API,传感器触发时直接将数据写入在线表格,利用表格自带的图表功能实现可视化
- 操作步骤:
- 登录Google Cloud控制台,创建项目并启用Google Sheets API,生成服务账号密钥(JSON格式),下载到树莓派本地
- 创建新的Google Sheet,将编辑权限分享给服务账号密钥中
client_email字段对应的邮箱 - 安装依赖库:
pip install gspread oauth2client - 修改原脚本实现数据同步:
import RPi.GPIO as GPIO import time import csv from datetime import datetime import gspread from oauth2client.service_account import ServiceAccountCredentials # Google Sheets配置 scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] creds = ServiceAccountCredentials.from_json_keyfile_name('/home/pi/your-service-key.json', scope) client = gspread.authorize(creds) sheet = client.open('燃气监测数据').sheet1 # 替换为你的表格名称 GPIO.setmode(GPIO.BOARD) GPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_UP) counter = 0 current_state = True prev_state = True while True: current_state = GPIO.input(15) if (current_state == False) and (prev_state == True): counter = counter + 1 print(counter) # 优化CSV写入:一行存储计数器+时间,便于后续读取 with open('/home/pi/gas_newfile.csv', 'a', newline='') as csvfile: spamwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow([str(counter), str(datetime.now())]) # 同步到Google Sheets try: sheet.append_row([datetime.now().strftime('%Y-%m-%d %H:%M:%S'), counter]) except Exception as e: print(f"同步失败: {e}") prev_state = current_state time.sleep(0.1) - 完成后打开Google Sheet即可看到实时数据,通过「插入」>「图表」一键生成折线图、柱状图等可视化报表
方案2:本地网页+内网穿透(无需第三方云服务)
- 核心逻辑:用Flask搭建轻量本地网页展示数据,通过内网穿透工具实现外网访问
- 操作步骤:
- 安装Flask:
pip install flask - 创建Flask服务文件
app.py:from flask import Flask, render_template_string import csv from datetime import datetime app = Flask(__name__) @app.route('/') def show_data(): data = [] try: with open('/home/pi/gas_newfile.csv', 'r') as f: reader = csv.reader(f, delimiter=' ') # 适配原脚本的两行一组数据格式 rows = list(reader) for i in range(0, len(rows), 2): if i+1 < len(rows): data.append({'count': rows[i][0], 'time': rows[i+1][0]}) except FileNotFoundError: data = [] # 内嵌Chart.js实现图表可视化 html_template = ''' <!DOCTYPE html> <html> <head> <title>燃气消耗监测</title> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> </head> <body> <h1>燃气消耗数据</h1> <table border="1"> <tr><th>时间</th><th>累计消耗次数</th></tr> {% for item in data %} <tr><td>{{ item.time }}</td><td>{{ item.count }}</td></tr> {% endfor %} </table> <div style="width: 80%; margin: 20px auto;"> <canvas id="gasChart"></canvas> </div> <script> const ctx = document.getElementById('gasChart').getContext('2d'); const times = {{ [item.time for item in data]|tojson }}; const counts = {{ [item.count for item in data]|tojson }}; new Chart(ctx, { type: 'line', data: { labels: times, datasets: [{ label: '累计燃气消耗', data: counts, borderColor: 'rgb(75, 192, 192)', tension: 0.1 }] } }); </script> </body> </html> ''' return render_template_string(html_template, data=data) if __name__ == '__main__': app.run(host='0.0.0.0', port=5000) - 运行
python app.py,同一内网设备访问树莓派IP:5000即可查看数据和图表 - 内网穿透:下载ngrok到树莓派,执行
./ngrok http 5000,获取生成的外网地址,即可随时远程访问
- 安装Flask:
方案3:ThingSpeak 物联网平台(专为设备数据设计,免费易用)
- 核心逻辑:通过HTTP请求直接上传数据到ThingSpeak,平台自带可视化与告警功能
- 操作步骤:
- 注册ThingSpeak账号,创建新Channel并添加一个字段(如「燃气计数」)
- 获取Channel的Write API Key
- 安装依赖库:
pip install requests - 修改原脚本添加数据上传逻辑:
# 顶部导入requests import requests # 传感器触发时插入以下代码 thing_speak_url = f"https://api.thingspeak.com/update?api_key=你的WriteAPIKey&field1={counter}" try: requests.get(thing_speak_url) except Exception as e: print(f"上传失败: {e}") - 上传成功后,进入Channel页面即可查看实时数据,还可配置图表、数据导出与异常告警
原脚本优化建议
- 将原脚本中两行写入的格式改为一行存储计数器+时间:
spamwriter.writerow([str(counter), str(datetime.now())]),便于后续数据读取 - 添加异常捕获逻辑,避免文件写入或数据上传失败导致脚本崩溃
- 定时备份CSV文件,防止数据丢失
内容的提问来源于stack exchange,提问作者Carto_
相关产品推荐
相关产品推荐

