# 读取树莓派4B处理器(CPU)的实时温度

树莓派发布4B后,性能提升了不少,但是温度也是高的不行,所以最好配置一个小风扇和散热片还是比较好的,效果明显。

# 1.Shell命令读取

# 打开终端

cd /sys/class/thermal/thermal_zone0 
1

# 查看温度

cat temp
1

# **树莓派的返回值 **

35050
1

返回值除以1000为当前CPU温度值。即当前温度为53摄氏度。如下图所示

# 2.编写一段c语言程序读取

# 程序源代码

温度是在   /sys/class/thermal/thermal_zone0/temp   文件下看的

# 编写代码

创建程序文件 read_cpu_temp.c  并打开编写代码

//读取树莓派4B处理器(CPU)的实时温度
// 编译
// gcc -o read_cpu_temp read_cpu_temp.c
// 运行
// ./read_cpu_temp

#include<stdio.h>
#include<stdlib.h>

#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>

#define TEMP_PATH "/sys/class/thermal/thermal_zone0/temp"
#define MAX_SIZE 32

int main(void)
{
    int fd;
    double temp = 0;
    char buffer[MAX_SIZE];
    int i;

    while(i < 100)
    {
        i+=1;

        //延时1s
        sleep(1);

        //打开文件
        fd = open(TEMP_PATH,O_RDONLY);
        if(fd < 0)
        {
            fprintf(stderr,"Failed to open thermal_zone0/temp\n");
            return - 1;
        }

        //读取文件
        if(read(fd,buffer,MAX_SIZE) < 0)
        {
            fprintf(stderr,"Failed to read temp\n");
            return -1;
        }

        //计算温度值
        temp = atoi(buffer) / 1000.0;

        //打印输出温度
        printf("Temp:%.4f\n",temp);

        //关闭文件
        close(fd);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

# 编译运行结果

gcc -o read_cpu_temp read_cpu_temp.c
1

编译程序出现三个警告,可以不用管它,生成可以执行文件read_cpu_temp

输入./read_cpu_temp运行程序

./read_cpu_temp
1

(我安装了风扇和散热片以及外壳,大概平均在36摄氏度左右)

# 3. 编写Erlang程序读取

# 编写代码

创建程序文件 read_cpu_temp.erl 并打开编写代码

%%%-------------------------------------------------------------------
%%% @author SummerGao
%%% @copyright (C) 2020, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 15. 7月 2020 13:59
%%%-------------------------------------------------------------------
-module(read_cpu_temp).
-author("SummerGao").

%% API
-export([loop/0]).

loop() ->
  {ok, Original} = file:read_file("/sys/class/thermal/thermal_zone0/temp"),
  [A, _] = binary:split(Original, [<<"\n">>]),
  T = binary_to_integer(A) / 1000,
  io:format("Temp ℃ : ~p~n", [T]),
  timer:sleep(1000),
  loop()
.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# 编译运行结果

Erlang/OTP 22 [erts-10.4] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1]

Eshell V10.4  (abort with ^G)
1> c(read_cpu_temp).    
{ok,read_cpu_temp}
2> c(read_cpu_temp).

1
2
3
4
5
6
7

# 4. 获取硬件相关信息

# 查看cpu信息

lscpu
1

# 查看内存信息

free -h
1

Last Updated: 11/1/2020, 2:25:27 PM