简体   繁体   English

在 Raspberry Pi 4 (Ubuntu 20.04.1) 中运行自定义 bash 脚本以控制 GPIO 的 CPU 使用率高

[英]High CPU usage running a custom bash script in Raspberry Pi 4 (Ubuntu 20.04.1) to control GPIO

I wrote a bash script to turn GPIO on/off to control a fan, but it's causing high CPU usage and I cant figure out why.我编写了一个 bash 脚本来打开/关闭 GPIO 以控制风扇,但它导致 CPU 使用率高,我不知道为什么。

It works but whenever it changes state from off to on or vice versa , the script freezes causing high CPU usage and after about 5 min it changes state and CPU usage returns back to normal.它可以工作,但是每当它从关闭状态变为开启状态或反之亦然时,脚本会冻结,导致 CPU 使用率过高,大约 5 分钟后,它会更改状态并且 CPU 使用率恢复正常。 And the problem repeats again after about 20-60 seconds.大约 20-60 秒后问题再次出现。

Can someone please help me understand what's wrong with my script?有人可以帮助我了解我的脚本有什么问题吗?

[Raspberry Pi 4 running Ubuntu 20.04] [树莓派 4 运行 Ubuntu 20.04]

#!/bin/bash
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin"

gpio -g mode 3 out

on=48000
off=44000

while true; do
    cpu=$(</sys/class/thermal/thermal_zone0/temp)    # get CPU temperature

    if (( "$cpu" > "$on" )); then
        gpio -g write 3 1    # turn fan ON
        echo "CPU Hot"
        sleep 60
    fi

    if (( "$off" > "$cpu" )); then
        echo "CPU Cool."
        gpio -g write 3 0    # turn fan OFF
        sleep 5
    fi
done

Okay so I was able to solve the problem, thanks to @shellter...好的,所以我能够解决问题,感谢@shellter ...

The problem was that the script did not have any condition to handle when the CPU temperature was between 4800 and 4400问题是,当CPU温度在48004400之间时,脚本没有任何condition处理

The basic idea of the solution is:该解决方案的基本思想是:

if (CPU is Hot); then
    turn fan ON
    set boolean = true
    sleep 60 sec

else if (CPU is Cool); then
    turn fan OFF
    set boolean = false
    sleep 5 sec

else (when CPU is neither Hot OR Cool.. somewhere between 4400 && 4800)

    if (boolean is true.. meaning CPU didn't go below 4400); then
        sleep 60 sec

    else (boolean is false.. meaning CPU didn't go above 4800); then
        sleep 5 sec 

The working code is:工作代码是:

#!/bin/bash
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin"

gpio -g mode 3 out

on=48000
off=44000
hot=false

while true; do
    cpu=$(</sys/class/thermal/thermal_zone0/temp)

    if (( "$cpu" > "$on" )); then
        echo "CPU Hot"
        hot=true
        gpio -g write 3 1    # turn fan ON
        sleep 60

    elif (( "$off" > "$cpu" )); then
        echo "CPU Cool."
        hot=false
        gpio -g write 3 0    # turn fan OFF
        sleep 5

    else
        if [ "$hot" = true ]; then
            echo "CPU still Hot"
            sleep 60
        else
            echo "CPU Cool"
            sleep 5
        fi
    fi
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM