Files
RPI-GPIO-fan-temp-control-o…/fan-temp-sensor.md
2025-07-23 22:21:49 +02:00

2.5 KiB

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

  1. The script accesses the DS18B20 sensor data from the Linux 1-Wire interface (/sys/bus/w1/devices/).
  2. It parses the temperature output and converts it to degrees Celsius.
  3. Based on the temperature:
    • If ≥ 46°C, the fan is turned on
    • If ≤ 40°C, the fan is turned off
  4. GPIO pin 18 is used to control the fan via the pinctrl utility.

📌 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)
  • pinctrl utility 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

  1. Make sure the sensor is connected and recognized under /sys/bus/w1/devices/.

  2. Update the device_folder variable 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 / elif block 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

📂 File Structure


📌 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-gpio
  • gpio (from WiringPi)
  • Python libraries like RPi.GPIO or gpiozero