Temperature-Based Fan Speed Control Using Arduino + L298N

Automatically adjust the fan speed based on the measured temperature using the DHT11 sensor and L298N motor driver.

Components Required:

ComponentQty
Arduino Uno/Nano1
L298N Motor Driver1
DHT11 or DHT22 Sensor1
DC Fan (5V or 12V)1
Power Supply (for fan)1
Jumper Wires
Breadboard (optional)

Wiring Connection:

Fan to L298N:

  • Fan +OUT1
  • Fan –OUT2

L298N to Arduino:

L298N PinArduino PinNotes
ENAD5PWM pin for speed control
IN1D6Direction control
IN2D7Direction control
GNDGNDCommon ground
12V/5VExternal power for fan

Important: Do not power the fan from Arduino 5V pin. Use an external 5V or 12V supply depending on your fan rating.


DHT11 Sensor to Arduino:

  • VCC → 5V
  • GND → GND
  • DATA → D2

Arduino Code:

Install Adafruit DHT sensor library before uploading:

#include <DHT.h>

#define DHTPIN 2
#define DHTTYPE DHT11

#define ENA 5     // PWM pin for fan speed
#define IN1 6
#define IN2 7

#define MIN_TEMP 25   // Fan starts at 25°C
#define MAX_TEMP 40   // Max fan speed at 40°C

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  dht.begin();

  pinMode(ENA, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);

  // Set fan direction (always forward)
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
}

void loop() {
  float temp = dht.readTemperature();

  if (isnan(temp)) {
    Serial.println("Failed to read from DHT sensor!");
    delay(2000);
    return;
  }

  Serial.print("Temperature: ");
  Serial.print(temp);
  Serial.println("°C");

  int fanSpeed = 0;

  if (temp <= MIN_TEMP) {
    fanSpeed = 0; // Fan OFF
  } else if (temp >= MAX_TEMP) {
    fanSpeed = 255; // Full speed
  } else {
    fanSpeed = map(temp, MIN_TEMP, MAX_TEMP, 100, 255);
  }

  analogWrite(ENA, fanSpeed);  // Set fan speed
  Serial.print("Fan PWM Speed: ");
  Serial.println(fanSpeed);

  delay(2000);
}

How It Works:

  • When temperature is below 25°C → Fan OFF
  • Between 25°C–40°C → Fan speed increases linearly
  • At 40°C or above → Fan runs at full speed

Optional Add-ons:

  • Add an OLED/LCD display to show real-time temp and speed.
  • Add a buzzer to alert on overheat (>45°C).
  • Use EEPROM to store last set temperature threshold.