问题描述
我写了一个bash脚本来打开/关闭GPIO以控制风扇,但是这导致CPU使用率很高,我不知道为什么。
它可以工作,但是无论何时将状态从关闭更改为打开,反之亦然,脚本会冻结,从而导致CPU使用率过高,大约5分钟后,脚本会更改状态,CPU使用率会恢复正常。大约20-60秒后问题再次出现。
有人可以帮我了解我的脚本有什么问题吗?
[运行Ubuntu 20.04的Raspberry Pi 4]
#!/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温度在condition
和4800
之间时,脚本没有任何4400
要处理
解决方案的基本思想是:
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