Scott

获取树莓派的温度 2 years ago

go
raspberry
2531个字符
共有128人围观

why

树莓派在日常生活中 担任了不少工作 平日休息的时候 它还孜孜不倦的工作着

看它如此勤劳踏实 又任劳任怨 再瞧瞧它瘦小的身板与外面的烈日炎炎形成的强烈反差

我不禁有些心疼 是不是该人性化一些 给咱的树莓派也降降温?

方案

关于降温,在温控开关的加持下,我有2套方案:

  • 1, 风扇降温:优点操作简单;缺点噪音大,运转占比时间长
  • 2, 水冷降温:优点能狠狠地把温度压到某个范围(我用的是这个);缺点:需要自己动手组装,要点成本(如果你想给树莓派组装一套水冷系统,可以点击页面最底部的email私密我。)

如果你通过pin脚来控制风扇的话,那么获取树莓派温度是个绕不开的问题

原理很简单,CPU会时时把温度写入/sys/class/thermal/thermal_zone0/temp这个文件中,我们要做的就是读取并解析

$ cat /sys/class/thermal/thermal_zone0/temp                    
41868

来看看下面2个实现:

golang版

package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"strconv"
	"strings"
	"time"
)

func main() {
	for {
		time.Sleep(time.Second)
		fmt.Printf("%s: CPU 温度 %.2f\n", time.Now().Format("2006-01-02 15:03:04"), GetTemperatureFromPi())
	}
}

func isExist(file string) bool {
	_, err := os.Stat(file)
	if err != nil {
		return false
	}
	return true
}

//get temperature of raspberry pi
func GetTemperatureFromPi() float64 {
	var result float64
	var file = "/sys/class/thermal/thermal_zone0/temp"
	if isExist(file) {
		bs, err := ioutil.ReadFile(file)
		if err != nil {
			return 0
		}
		data := strings.TrimSpace(string(bs))
		result, _ = strconv.ParseFloat(data, 64)
		result, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", result/1000), 64)
	}
	return result
}

python版

#!/usr/bin/env python3
import os
import time

def main():
    """
    Program to demonstrate how to obtain the current value of the CPU temperature.
    """
    print('Current CPU temperature is {:.2f} degrees Celsius.'.format(get_cpu_temp()))
def get_cpu_temp():
    """
    Obtains the current value of the CPU temperature.
    :returns: Current value of the CPU temperature if successful, zero value otherwise.
    :rtype: float
    """
    # Initialize the result.
    result = 0.0
    # The first line in this file holds the CPU temperature as an integer times 1000.
    # Read the first line and remove the newline character at the end of the string.
    if os.path.isfile('/sys/class/thermal/thermal_zone0/temp'):
        with open('/sys/class/thermal/thermal_zone0/temp') as f:
            line = f.readline().strip()
        # Test if the string is an integer as expected.
        if line.isdigit():
            # Convert the string with the CPU temperature to a float in degrees Celsius.
            result = float(line) / 1000
    # Give the result back to the caller.
    return result
if __name__ == "__main__":
    while 1:
        time.sleep(1) # 1 second
        main()
        pass

我的树莓派自从装了水冷后,即使夏日炎炎,超负载,温度也能压到45度以下,来看看效果: