[英]Raspberry Pi Control LED Base on CPU Temperature with Python
我想要一些幫助,讓這個 python 代碼與我的 Raspberry Pi 一起工作。 目標是根據 CPU溫度范圍一次打開 3 個 LED 中的 1 個(綠色、黃色和紅色)。
這表示:
我是編碼新手,到目前為止,我可以打印溫度,並且無論 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()
很酷的項目,你的代碼很接近。
我認為主要問題是您從vcgencmd
獲得了一個string
,並且您試圖將其與一個數字進行比較。 我會 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()
還要注意elif
的使用,這使得測試三種情況中的最后一種變得更加容易。
我還使用了一個regex
來從vcgencmd
字符串中提取數字,因為文本可能會隨着不同的國際化而改變——這里是 YMMV。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.