Raspberry Pi 的 CPU 溫度資訊儲存在系統的虛擬檔案中,可以透過讀取該檔案來取得目前的溫度數值。這在監控 Pi 的運行狀態,或判斷是否需要加裝散熱片時非常實用。
溫度資料來源
Linux 系統將 CPU 溫度儲存在以下路徑:
1
|
/sys/class/thermal/thermal_zone0/temp
|
這個檔案裡的數值單位是千分之一攝氏度(毫攝氏度),例如讀到 47500 代表 47.5°C。
原始 Python 2 程式碼
1
2
3
4
5
|
# cpuTemp.py (Python 2)
f = open("/sys/class/thermal/thermal_zone0/temp", "r")
for t in f:
print "CPU temp:" + t[:2] + "." + t[2:5]
f.close()
|
改良版 Python 3 程式碼
Python 3 的 print 改為函式,字串處理上也建議改用整數除法,以下是較完整的版本:
1
2
3
4
5
6
7
8
9
|
# cpuTemp.py (Python 3)
def get_cpu_temperature():
with open("/sys/class/thermal/thermal_zone0/temp", "r") as f:
temp_raw = int(f.read().strip())
return temp_raw / 1000.0
if __name__ == "__main__":
temp = get_cpu_temperature()
print(f"CPU 溫度:{temp:.1f} °C")
|
使用 with 語法可以確保檔案自動關閉,即使發生例外也不會有資源洩漏的問題。
持續監控(每秒更新)
1
2
3
4
5
6
7
8
9
10
|
import time
def get_cpu_temperature():
with open("/sys/class/thermal/thermal_zone0/temp", "r") as f:
return int(f.read().strip()) / 1000.0
while True:
temp = get_cpu_temperature()
print(f"CPU 溫度:{temp:.1f} °C")
time.sleep(1)
|
使用指令查詢(不用寫程式)
也可以直接在終端機使用以下指令查詢:
1
2
3
4
5
|
# 直接讀取原始數值
cat /sys/class/thermal/thermal_zone0/temp
# 使用 vcgencmd(Raspberry Pi 專屬工具)
vcgencmd measure_temp
|
vcgencmd 是 Raspberry Pi 內建工具,輸出格式更易讀,例如 temp=47.5'C。
實際應用場景
- 監控 Pi 是否過熱(一般建議不超過 80°C,超過可能降頻)
- 搭配 GPIO 控制風扇,達到溫控自動散熱
- 記錄溫度到 CSV 或資料庫,進行長時間趨勢分析