NanoPi、树莓派等开发板获取CPU温度

linux / 2019年01月21日 10时35分 / 11131人浏览

NanoPi、树莓派等开发板获取CPU温度

因为在linux系统中任何设备的操作都可以抽象成为文件的读写,并且通过读取/sys/class/thermal/thermal_zone0/temp文件中的内容便获得CPU的温度。

一、shell命令操作

 1、输入命令,进入到/sys/class/thermal/thermal_zone0目录下:
cd /sys/class/thermal/thermal_zone0
 2、我们在输入:ls,查看有哪些文件:
 3、再用命令:cat temp得到温度值(除以1000才是具体的温度值),见下图:

二、c语言文件操作:

新建一个cputemp.c文件:
#include   
#include    
  
#include <sys/types.h>  
#include <sys/stat.h>  
#include  // for open
#include  // for close
  
#define TEMP_PATH "/sys/class/thermal/thermal_zone0/temp"  
#define MAX_SIZE 32  
int main(void)   
{  
	  int fd;  
	  double temp = 0;  
	  char buf[MAX_SIZE];  
	  
	  // 打开/sys/class/thermal/thermal_zone0/temp  
	  fd = open(TEMP_PATH, O_RDONLY);  
	 if (fd < 0) {  
		 fprintf(stderr, "failed to open thermal_zone0/temp\n");  
		 return -1;  
	}  
	  
	 // 读取内容  
	 if (read(fd, buf, MAX_SIZE) < 0) {  
		 fprintf(stderr, "failed to read temp\n");  
		 return -1;  
	}  
	  
	// 转换为浮点数打印  
	 temp = atoi(buf) / 1000.0;  
	 printf("temp:%.2f\n", temp);  
	  
	// 关闭文件  
	 close(fd);  
}  

#编译 gcc cputemp.c -o cputemp #执行 ./cputemp # 执行返回 temp: 23.01