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

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

我写了一个 bash 脚本来将 GPIO on/off 控制风扇,但它导致 CPU 使用率很高,我不知道为什么。

它有效,但每当它从关闭状态变为打开状态或反之亦然时,脚本会冻结,导致高 CPU 使用率,大约 5 分钟后它会改变状态和 CPU 使用率 [=30= 】 恢复正常。大约 20-60 秒后问题再次出现。

有人可以帮我理解我的脚本有什么问题吗?

[Raspberry Pi 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

好的所以我能够解决问题,感谢@shellter...

问题是当 CPU 温度介于 48004400

之间时,脚本没有任何要处理的 condition

解决的基本思路是:

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 

工作代码是:

#!/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