简体   繁体   中英

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.

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. And the problem repeats again after about 20-60 seconds.

Can someone please help me understand what's wrong with my script?

[Raspberry Pi 4 running 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...

The problem was that the script did not have any condition to handle when the CPU temperature was between 4800 and 4400

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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