通过gpio控制风扇,监测CPU温度,解决pwm风扇异响、频繁开关的问题。
1.电路设计
使用了S8550 PNP三极管,gpio低电平时风扇开启。
gpio高电平时3.3v,经实验S8050 NPN三极管无法驱动5v风扇
2.编写脚本
在/opt/中创建fan/fan.sh:
#!/bin/bash
# Pin number
fan=25
# The temperature at which the fan starts to work, in millimeters Celsius
on=60000
# The temperature at which the fan stops working, in millimeters Celsius
off=45000
#Whether it works forever, 0 is not
#forever=1
#Set the pin mode
gpio mode $fan out
while true
do
# Read the temperature
read temp</sys/class/thermal/thermal_zone0/temp
if ((temp>=on))
then
# On
gpio write $fan 0
#echo "on"
elif ((temp<=off))
then
# Off
gpio write $fan 1
#echo "off"
fi
# Check whether it works forever
#if ((forever==0))
#then
#break
#fi
sleep 10s
done
3.开机自启
创建fan.service
#Add permissions
sudo chmod +x /opt/fan/fan.sh
#Create by vim editor
sudo vim /etc/systemd/system/fan.service
添加
[Unit]
Description=Fan Control Script
[Service]
ExecStart=/opt/fan/fan.sh
[Install]
WantedBy=multi-user.target
回到命令行
#add to the configuration file
sudo systemctl daemon-reload
#Start when turned on
sudo systemctl enable fan
#Start now
sudo systemctl start fan
#Check the status
sudo systemctl status fan
#Test
sudo apt install stress
stress -c 50
以下是自动安装脚本:
install.sh
```bash
#!/bin/bash
# Get the directory where the script is located
SCRIPT_DIR="$(dirname "$0")"
# Ensure fan.sh has executable permissions
if [ ! -x "$SCRIPT_DIR/fan.sh" ]; then
echo "Setting fan.sh to be executable..."
sudo chmod +x "$SCRIPT_DIR/fan.sh"
fi
# Copy fan.service to /etc/systemd/system
if [ ! -f /etc/systemd/system/fan.service ]; then
echo "Copying fan.service to /etc/systemd/system..."
sudo cp "$SCRIPT_DIR/fan.service" /etc/systemd/system
else
echo "fan.service already exists, skipping copy..."
fi
# Reload the systemd manager configuration
echo "Reloading systemd manager configuration..."
sudo systemctl daemon-reload
# Enable the fan service
echo "Enabling fan service..."
sudo systemctl enable fan
# Start the fan service
echo "Starting fan service..."
sudo systemctl start fan
echo "Script execution completed."
```
运行效果:
```bash
#首次安装
$ ./install.sh
Copying fan.service to /etc/systemd/system...
Reloading systemd manager configuration...
Enabling fan service...
Created symlink /etc/systemd/system/multi-user.target.wants/fan.service → /etc/systemd/system/fan.service.
Starting fan service...
Script execution completed.
#第二次安装
$ ./install.sh
fan.service already exists, skipping copy...
Reloading systemd manager configuration...
Enabling fan service...
Starting fan service...
Script execution completed.
```
参考链接: