1 前言
嵌入式设备中,对于长时间工作的设备,特别是工控产品,一般会增加一个风扇为cpu主动散热。而风扇一般会选用可调速的,这样程序可以根据cpu温度实时调整风扇速度,以达到高温时能及时降低cpu温度,低温时节约功耗的目的。
2 获取cpu温度
cpu原厂提供的linux内核通常已经带有cpu温度检测驱动,并将温度信息映射到用户文件系统下,用户只需从该虚拟文件读取温度信息即可。cpu温度虚拟文件位于“/sys/devices/virtual/thermal”
或者“/sys/class/thermal”
下,命名为“thermal_zoneX”
,X表示cpu核温度检测节点,如果是多核cpu通常会有多个温度检测节点;使用其中一个即可,因为温度通常差异不大。
rk3399 ubuntu16 下cup核温度节点
root@firefly:/home# ls /sys/devices/virtual/thermal/
cooling_device0 cooling_device1 cooling_device2 thermal_zone0 thermal_zone1
root@firefly:/home# ls /sys/class/thermal/
cooling_device0 cooling_device1 cooling_device2 thermal_zone0 thermal_zone1
2.1 通过shell获取
root@firefly:/home# cat /sys/class/thermal/thermal_zone0/temp
42222
root@firefly:/home# cat /sys/class/thermal/thermal_zone1/temp
41666
其中温度单位是0.001℃,即是温度节点0“thermal_zone0”
当前温度为42.222℃。
2.2 通过watch实时刷新
通过watch命令,每2秒读取一次cpu温度输出到终端。
root@firefly:/home# watch -n 2 -d echo cpu temperature:[$(cat /sys/class/thermal/thermal_zone0/temp)]
Every 2.0s: echo cpu temperature:[42777] Thu Jul 30 16:02:05 2020
cpu temperature:[42777]
2.3 通过C语言读取
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define CPU_TEMP_FILE0 "/sys/devices/virtual/thermal/thermal_zone0/temp"
#define CPU_TEMP_FILE1 "/sys/devices/virtual/thermal/thermal_zone0/temp"
int main(int arc, char *argv[])
{
FILE *fp = NULL;
int temp = 0;
fp = fopen (CPU_TEMP_FILE0, "r");
if (fp < 0)
{
printf("open file failed,%s\n", strerror(errno));
}
for (;;)
{
fscanf(fp, "%d", &temp);
printf("cpu temperature: [%d.%d C]\n", temp/1000, temp%1000/100);
sleep(2);
}
fclose(fp);
return 0;
}
编译执行
root@firefly:/home# gcc cpu_temp.c -o cpu_temp
root@firefly:/home# ./cpu_temp
cpu temperature: [42.7 C]
cpu temperature: [42.7 C]
cpu temperature: [42.7 C]