分别用终端命令行,python语言,C语言,shell脚本编写查询CPU温度。
1)终端命令
vcgencmd measure_temp
2)python程序
1.安装vcgencmd:
sudo apt-get install vcgencmd
2.创建一个名为temp.py的文件
import subprocess
# 执行vcgencmd命令,获取CPU温度值
result = subprocess.check_output(["vcgencmd", "measure_temp"])
# 处理温度字符串,去掉无用字符
temp = float(result.decode().replace("temp=", "").replace("'C\n", ""))
print("CPU temperature = %.1f ℃" % temp)
3.运行代码:
sudo python temp.py
3)C语言程序
1.安装bcm2835库:
sudo apt-get install bcm2835
2.创建一个名为temp.c的文件
#include <bcm2835.h>
#include <stdio.h>
int main(int argc, char **argv)
{
if (!bcm2835_init())
return 1;
// 读取CPU温度寄存器的值
uint32_t raw = *(volatile uint32_t *)(0x7e00b078);
// 将寄存器的值转换为温度值
double temp = ((double)raw / 1000.0);
printf("CPU temperature = %.1f ℃\n", temp);
bcm2835_close();
return 0;
}
3.编译并运行代码:
gcc -o temp temp.c -lbcm2835
sudo ./temp
4)shell脚本程序
1.创建一个名为temp.sh的文件
#!/bin/bash
cpuTemp=$(cat /sys/class/thermal/thermal_zone0/temp)
echo "CPU温度:$((cpuTemp/1000))℃"
2.如果你想要定期查询CPU温度并将其保存到日志文件中,可以使用以下脚本:
#!/bin/bash
while true
do
cpuTemp=$(cat /sys/class/thermal/thermal_zone0/temp)
echo "$(date +"%Y-%m-%d %T") CPU温度:$((cpuTemp/1000))℃" >> temperature.log
sleep 60
done
这个脚本将会在无限循环中查询CPU温度,然后将时间和温度信息附加在 temperature.log
文件末尾,每隔60秒查询一次。你可以使用 Ctrl+C 键来中断这个脚本的执行。