树莓派:查询CPU温度的多种方式

分别用终端命令行,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 键来中断这个脚本的执行。

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值