[英]Raspberry Pi Control LED Base on CPU Temperature with Python
I'd like some help getting this python code to work with my Raspberry Pi.我想要一些帮助,让这个 python 代码与我的 Raspberry Pi 一起工作。 The goal is to turn on 1 of 3 LED's at a time ( Green, Yellow, and Red ) based on a CPU Temperature Range .
目标是根据 CPU温度范围一次打开 3 个 LED 中的 1 个(绿色、黄色和红色)。
This means:这表示:
I'm a newbie at coding, so far I can get the temperature to print and only the Red LED turns on and stays on regardless of CPU temperature.我是编码新手,到目前为止,我可以打印温度,并且无论 CPU 温度如何,只有红色 LED 会亮起并保持亮起。
import os
import time
import RPi.GPIO as GPIO
#GREEN=11
#YELLOW=10
#RED=9
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(11,GPIO.OUT)
GPIO.setup(10,GPIO.OUT)
GPIO.setup(9,GPIO.OUT)
def measure_temp():
temp = os.popen("vcgencmd measure_temp").readline()
return (temp.replace("temp=","").replace("'C",""))
while True:
measure_temp()
if measure_temp<32:
GPIO.output(11,GPIO.HIGH)
GPIO.output(10,GPIO.LOW)
GPIO.output(9,GPIO.LOW)
if measure_temp>37:
GPIO.output(9,GPIO.HIGH)
GPIO.output(10,GPIO.LOW)
GPIO.output(11,GPIO.LOW)
if measure_temp>32 or <37
GPIO.output(10,GPIO.HIGH)
GPIO.output(11,GPIO.LOW)
GPIO.output(9,GPIO.LOW)
print(measure_temp())
#cleanup
c.close()
GPIO.cleanup()
Cool project and your code is close.很酷的项目,你的代码很接近。
I think the main problem is that you get a string
from vcgencmd
and you are trying to compare that to a number.我认为主要问题是您从
vcgencmd
获得了一个string
,并且您试图将其与一个数字进行比较。 I would go with something more like this (untested):我会 go 更像这样的东西(未经测试):
#!/usr/bin/env python3
import os
import re
import time
import RPi.GPIO as GPIO
RED, YELLOW, GREEN = 9, 10, 11
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(RED,GPIO.OUT)
GPIO.setup(YELLOW,GPIO.OUT)
GPIO.setup(GREEN,GPIO.OUT)
def measure_temp():
output = os.popen("vcgencmd measure_temp").readline()
# Remove anything not like a digit or a decimal point
result = re.sub('[^0-9.]','', output)
return float(result)
while True:
temp = measure_temp()
if temp<32:
GPIO.output(GREEN,GPIO.HIGH)
GPIO.output(YELLOW,GPIO.LOW)
GPIO.output(RED,GPIO.LOW)
elif temp>37:
GPIO.output(RED,GPIO.HIGH)
GPIO.output(GREEN,GPIO.LOW)
GPIO.output(YELLOW,GPIO.LOW)
else:
GPIO.output(YELLOW,GPIO.HIGH)
GPIO.output(GREEN,GPIO.LOW)
GPIO.output(RED,GPIO.LOW)
print(temp)
# Let's not affect our temperature by running flat-out full-speed :-)
time.sleep(1)
#cleanup
c.close()
GPIO.cleanup()
Note also the use of elif
which makes it rather easier for testing the final one of your three cases.还要注意
elif
的使用,这使得测试三种情况中的最后一种变得更加容易。
I also went for a regex
to extract the number from the vcgencmd
string because the text may change with different internationalisation - YMMV here.我还使用了一个
regex
来从vcgencmd
字符串中提取数字,因为文本可能会随着不同的国际化而改变——这里是 YMMV。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.