你很接近了。这两行代码有问题:
temp = os.popen('vcgencmd measure_temp').readline()
if temp > 65:
这里的temp
是一个字符串。在尝试与整数进行比较之前,您需要将temp
转换为整数。假设您正在读取的行仅是一个对应于某个温度的十进制字符串,您只需调用int()
,如下所示:
temp = os.popen('vcgencmd measure_temp').readline()
temp = int(temp)
更新:鉴于你所发布的输出结果,我们可以使用正则表达式来匹配该输出结果。使用re
模块进行匹配。我们将把它放在一个函数中:
def measure_temp():
raw = os.popen('vcgencmd measure_temp').readline()
m = re.match("temp=(\d+\.?\d*)'C", raw)
if not m:
raise ValueError("Unexpected temperature string: " + raw)
return float(m.group(1))
temp = measure_temp()
注意,我在字符串中的实际温度小数周围使用了一个“捕获组”,并使用m.group(1)进行访问。
现在让我们把它放在一起。此外,当您的代码没有按预期工作时,包括一些“调试打印”非常有帮助,就像这样:
def measure_temp():
raw = os.popen('vcgencmd measure_temp').readline()
m = re.match("temp=(\d+\.?\d*)'C", raw)
if not m:
raise ValueError("Unexpected temperature string: " + raw)
return float(m.group(1))
temp = measure_temp()
print 'Temperature from vcgencmd: {}'.format(temp)
if temp > 65:
print 'Turning on GPIO 4'
GPIO.output(4, True)
else:
print 'Turning off GPIO 4'
GPIO.output(4, False)
基础部分搞定后,你还可能遇到以下问题:
你的脚本只能检查温度并切换 GPIO 一次。如果你希望它像一个恒温器一样运行,就需要使用 while
循环来重复执行这些操作。
如果你的 while
循环速度非常快,并且温度在你设定的阈值(65)左右波动,你会发现你的代码会不断地开关风扇。为了解决这个问题,你可以在系统中添加一些滞后效应。例如,如果你将家用恒温器(加热)设置为 70 度,当温度达到 69 度时,它会打开;但当温度达到 71 度时,它会关闭。或者,如果在过去 X 秒内已经改变了状态,它可能根本不会改变状态。
最简单的解决方法是在检查之间短暂地使用 sleep()
函数:
while True:
temp = os.popen('vcgencmd measure_temp').readline()
temp = int(temp)
print 'Temperature from vcgencmd: {}'.format(temp)
if temp > 65:
print 'Turning on GPIO 4'
GPIO.output(4, True)
else:
print 'Turning off GPIO 4'
GPIO.output(4, False)
time.sleep(5)
if int(temp) > 65:
另外,您没有在循环中运行任何内容,因此它将执行一次并完成。尝试在while循环内执行最后5行(包括读取temp)并延迟约0.1秒。 - GRAYgoose124measure_temp()
。 - Jonathon Reinhart