用于轮询树莓派内部SoC温度的Python脚本
我正在从多个来源拼凑一个脚本,用来监测我的树莓派内部的芯片温度。然后我想把这些数据传输到我的Plotly账户上。
我有一个半成品的脚本,但一旦读取到芯片温度,它就会无限期地持续发送这个温度。作为一个Python新手,我似乎无法弄明白如何在用户设定的时间间隔内获取温度,并不断用新的值更新它。我的代码如下:
#!/usr/bin/env python
import plotly.plotly as py # plotly library
from plotly.graph_objs import * # all plotly graph objects
import json # used to parse config.json
import time # timer functions
import datetime
import os # used to acquire internal SoC temperature
import sys
# Initialize some variables with your credentials
with open('./config.json') as config_file:
plotly_user_config = json.load(config_file)
username = plotly_user_config['plotly_username']
api_key = plotly_user_config['plotly_api_key']
stream_token = plotly_user_config['plotly_streaming_tokens'][0]
# Initialize a Plotly Object
py.sign_in(username, api_key)
# Initialize your graph (not streaming yet)
data = [Scatter(
x=[],y=[],
mode='lines+markers',
stream={'token': stream_token, 'maxpoints': 1000},
name='UCBPD')
]
layout = Layout(
title='Raspberry Pi Temperature',
xaxis={'autorange': True, 'title': 'Time of Day'},
yaxis={'autorange': True, 'title': 'Degrees (Celsuis)'}
)
your_graph_url = py.plot(Figure(data=data, layout=layout), filename='Raspberry Pi Temp', auto_open=False)
# Acquire internal SoC temperature
cmd = '/opt/vc/bin/vcgencmd measure_temp'
line = os.popen(cmd).readline().strip()
if "error" in line:
print "Error ... is your firmware up-to-date? Run rpi-update"
else:
# line now contains something like: temp=41.2'C
# to get the temperature, split on =, and then on '
temp = line.split('=')[1].split("'")[0]
# Initialize the Plotly Streaming Object
stream = py.Stream(stream_token)
stream.open()
# Start looping and streaming!
while True:
stream.write({'x': datetime.datetime.now(), 'y': temp})
time.sleep(1) # delay between stream posts
1 个回答
1
无论是什么代码在设置 temp
(温度)这个变量的值,都必须放在循环里,不然这个温度变量就不会改变。
如果你还是遇到问题,可以先把配置文件和图表功能去掉,直接把原始读数打印到控制台上,这样会简单一些。