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