Raspberry Pi Fan Control Script
This Python script monitors the temperature of a Raspberry Pi using a 1-Wire digital temperature sensor (e.g., DS18B20) and controls a connected fan via GPIO. It is designed to help maintain optimal operating temperatures by automatically turning the fan on or off depending on the measured temperature.
🛠️ Features
- Reads temperature data from a 1-Wire sensor (
DS18B20) - Uses GPIO pin control to activate/deactivate a fan
- Customizable temperature thresholds for fan activation
- Simple, lightweight script suitable for cron jobs or long-running processes
💡 How It Works
- The script accesses the DS18B20 sensor data from the Linux 1-Wire interface (
/sys/bus/w1/devices/). - It parses the temperature output and converts it to degrees Celsius.
- Based on the temperature:
- If
≥ 46°C, the fan is turned on - If
≤ 40°C, the fan is turned off
- If
- GPIO pin 18 is used to control the fan via the
pinctrlutility.
📌 Prerequisites
- Raspberry Pi (any model with GPIO and 1-Wire support)
- 1-Wire temperature sensor (e.g., DS18B20) connected and configured
- GPIO fan connected to pin 18 (can be changed in script)
pinctrlutility installed and configured- Python 3
Enable the 1-Wire interface on the Pi using raspi-config or by adding this line to /boot/config.txt:
dtoverlay=w1-gpio
Then reboot:
sudo reboot
📄 Usage
-
Make sure the sensor is connected and recognized under
/sys/bus/w1/devices/. -
Update the
device_foldervariable if your sensor ID differs from the one in the script:device_folder = glob.glob(base_dir + '28-*')[0]
The script will continuously monitor the temperature and control the fan accordingly.
⚙️ Customization
- Temperature thresholds: Modify the values in the
if/elifblock to change when the fan turns on/off. - GPIO pin: Change the pin number in
pinctrl set 18 ...if using a different GPIO.
🧪 Example Output
Temperature: 41.25 °C
Temperature: 43.12 °C
Temperature: 46.05 °C # Fan turns on here
Temperature: 39.80 °C # Fan turns off here
📌 Note
This script uses pinctrl, which may not be installed on all systems by default. You may need to substitute pinctrl with another GPIO control utility such as:
raspi-gpiogpio(from WiringPi)- Python libraries like
RPi.GPIOorgpiozero