Raspberry Pi - Cooling System using DS18B20 Temperature Sensor

This tutorial instructs you how to regulate temperature with the help of a Raspberry Pi, a fan and a DS18B20 temperature sensor.

If you would like to use either a DHT11 or DHT22 instead of the DS18B20 sensor, please refer to Raspberry Pi - Cooling System using DHT Sensor.

Hardware Preparation

1×Raspberry Pi 4 Model B
1×DS18B20 Temperature Sensor (WITH Adapter)
1×DS18B20 Temperature Sensor (WITHOUT Adapter)
1×4.7 kΩ resistor
1×12V DC Cooling Fan
1×(Alternative) 5V DC Cooling Fan
1×12V Power Adapter
1×DC Power Jack
1×Jumper Wires
1×(Optional) Screw Terminal Adapter for Raspberry Pi

Or you can buy the following sensor kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you. We appreciate your support.

Buy Note: Many DS18B20 sensors available in the market are unreliable. We strongly recommend buying the sensor from the DIYables brand using the link provided above. We tested it, and it worked reliably.

Overview of Cooling Fan and DS18B20 Temperature Sensor

The fan utilized in this tutorial requires a 12v power supply. If the power is supplied, the fan will turn on, and if not, it will not. To control the fan with Raspberry Pi, a relay must be placed between them.

If you are unfamiliar with temperature sensors and fans (their pinouts, how they operate, how to program them, etc.), the following tutorials can help you out:

Wiring Diagram

The wiring diagram between Raspberry Pi and cooling fan system

This image is created using Fritzing. Click to enlarge image

We recommend buying a DS18B20 sensor along with its accompanying wiring adapter for a seamless setup. This adapter includes an integrated resistor, removing the need for an additional resistor in the wiring.

How System Works

  • The Raspberry Pi will take a reading from the temperature sensor.
  • If the temperature is higher than the maximum allowed, the fan will be activated by the Raspberry Pi.
  • When the temperature drops below the minimum accepted level, the Raspberry Pi will switch off the fan.

The loop is repeated continuously.

If you wish to activate and deactivate the fan when the temperature is above or below a certain value, all you have to do is set the upper and lower limits to the same number.

Raspberry Pi Code for Cooling System with DS18B20 sensor

Let's write the code that make the Raspberry Pi activate the fan when the temperature is higher than 25°C and will keep it running until the temperature drops below 20°C.

Detailed Instructions

  • Make sure you have Raspbian or any other Raspberry Pi compatible operating system installed on your Pi.
  • Make sure your Raspberry Pi is connected to the same local network as your PC.
  • Make sure your Raspberry Pi is connected to the internet if you need to install some libraries.
  • If this is the first time you use Raspberry Pi, See how to set up the Raspberry Pi
  • Connect your PC to the Raspberry Pi via SSH using the built-in SSH client on Linux and macOS or PuTTY on Windows. See to how connect your PC to Raspberry Pi via SSH.
  • Make sure you have the RPi.GPIO library installed. If not, install it using the following command:
sudo apt-get update sudo apt-get install python3-rpi.gpio
  • Prior to utilizing the DS18B20 temperature sensor with a Raspberry Pi, we need to enable 1-Wire interface on Raspberry Pi. See How to enable 1-Wire interface on Raspberry Pi
  • Install the library for DS18B20 temperature sensor by running the following command:
pip install w1thermsensor
  • Create a Python script file cooling.py and add the following code:
# This Raspberry Pi code was developed by newbiely.com # This Raspberry Pi code is made available for public use without any restriction # For comprehensive instructions and wiring diagrams, please visit: # https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-cooling-system-using-ds18b20-temperature-sensor from w1thermsensor import W1ThermSensor import RPi.GPIO as GPIO import time # Constants THRESHOLD_ON = 25 # Upper threshold of temperature, change to your desired value THRESHOLD_OFF = 20 # Lower threshold of temperature, change to your desired value FAN_PIN = 21 # GPIO pin connected to relay, change to your desired GPIO pin # Setup GPIO.setmode(GPIO.BCM) GPIO.setup(FAN_PIN, GPIO.OUT) def find_ds18b20_sensor(): for sensor in W1ThermSensor.get_available_sensors(): if sensor.type == W1ThermSensor.THERM_SENSOR_DS18B20: return sensor return None def read_temperature(sensor): try: temperature_celsius = sensor.get_temperature() return temperature_celsius except Exception as e: print(f"Error reading temperature: {e}") return None def control_fan(temperature): if temperature is not None: if temperature > THRESHOLD_ON: print("The fan is turned on") GPIO.output(FAN_PIN, GPIO.HIGH) elif temperature < THRESHOLD_OFF: print("The fan is turned off") GPIO.output(FAN_PIN, GPIO.LOW) # Find DS18B20 sensor ds18b20_sensor = find_ds18b20_sensor() if ds18b20_sensor is not None: print(f"DS18B20 Sensor found: {ds18b20_sensor.id}") try: while True: temperature = read_temperature(ds18b20_sensor) control_fan(temperature) time.sleep(0.5) except KeyboardInterrupt: pass finally: GPIO.cleanup() else: print("DS18B20 Sensor not found.")
  • Save the file and run the Python script by executing the following command in the terminal:
python3 cooling.py

The script runs in an infinite loop continuously until you press Ctrl + C in the terminal.

  • Change the temperature of the environment around the sensor.
  • Check the status of the fan on the Serial Monitor.

Advanced Knowledge

This controlling method is referred to as an on-off controller, which is also known as a signaller or "bang-bang" controller. It is easy to implement this method.

An alternative approach, known as the PID controller, exists. This method of temperature control is more stable, but it is complex and challenging to comprehend and implement. As a result, the PID controller is not widely used.

Video Tutorial


  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!