Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 37 ยท Projects and Practice

Project: Thermostat Fan Controller

Build a temperature-controlled fan: read a sensor, add hysteresis to avoid chatter, scale fan speed with PWM, show status, and simulate a room to tune the controller.

A thermostat is a classic control problem: measure, compare with a target, act. Do it naively and the fan will rattle on and off when the temperature sits near the threshold. Do it well and it runs smoothly, quietly and efficiently. This project builds two controllers, an on/off one with hysteresis and a proportional one that scales the PWM speed with temperature.

Real sensors, fans and Arduino boards cannot run on this site, so the Arduino code is read-only. The C programs are labelled stand-ins that simulate a room that warms up and cools down, which lets you tune the controller by running experiments.

What you need

  • Arduino Uno or Nano
  • Temperature sensor: TMP36 on A0 (or a DHT22; see temperature sensors)
  • A small 5 V or 12 V DC fan, an N-channel logic-level MOSFET (IRLZ44N) or a transistor, a flyback diode, a 220 ohm gate resistor, and a separate supply for the fan if it draws more than about 100 mA (the wiring and reasons are in DC motors)
  • A potentiometer on A1 to set the target temperature (optional)
  • A 16x2 LCD or just the serial monitor for status

The MOSFET gate goes to pin 9 (PWM) through the resistor; the fan sits between the supply and the drain; the source is connected to ground, shared with the Arduino. The diode protects against switch-off spikes.

Controller 1: on/off with hysteresis

A basic rule: fan on above 28 C, off below 28 C. Near 28 C the reading fluctuates by a fraction of a degree, so the fan switches on and off again and again ("chatter"), which wears out the fan and relays. Hysteresis separates the two thresholds: on at 28.0 C, off at 26.0 C. Between them, the controller keeps its previous state.

stateDiagram-v2
  [*] --> FanOff
  FanOff --> FanOn: temperature above 28.0
  FanOn --> FanOff: temperature below 26.0

The gap between thresholds is the dead band. Wider means fewer switches but a larger temperature swing.

C++
const int SENSOR_PIN = A0;
const int FAN_PIN = 9;

const float ON_ABOVE = 28.0;
const float OFF_BELOW = 26.0;
bool fanOn = false;

float readCelsius() {
  long total = 0;
  for (int i = 0; i < 8; i++) total += analogRead(SENSOR_PIN);
  return ((total / 8.0) * (5.0 / 1023.0) - 0.5) * 100.0;
}

void setup() {
  pinMode(FAN_PIN, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  float t = readCelsius();

  if (!fanOn && t > ON_ABOVE) {
    fanOn = true;
  } else if (fanOn && t < OFF_BELOW) {
    fanOn = false;
  }
  digitalWrite(FAN_PIN, fanOn ? HIGH : LOW);

  Serial.print(t, 1);
  Serial.print(" C  fan ");
  Serial.println(fanOn ? "ON" : "off");
  delay(1000);
}

Controller 2: proportional speed with PWM

Instead of full speed or nothing, scale the speed: off below 26 C, minimum useful speed at 26 C, full speed at 34 C and above, linear in between. A fan needs a minimum duty to start spinning (often 30 to 40 percent), so the map starts at that value rather than at zero.

C++
int fanSpeedFor(float t) {
  const float T_LOW = 26.0;
  const float T_HIGH = 34.0;
  const int PWM_MIN = 90;           // about 35% duty: enough to start the fan
  const int PWM_MAX = 255;

  if (t <= T_LOW) return 0;
  if (t >= T_HIGH) return PWM_MAX;
  return PWM_MIN + (int)((t - T_LOW) * (PWM_MAX - PWM_MIN) / (T_HIGH - T_LOW));
}

void loop() {
  float t = readCelsius();
  analogWrite(FAN_PIN, fanSpeedFor(t));
  // print and wait...
}

This is a proportional controller: the response grows with the error. With a dead zone at the low end it also acts like hysteresis, but a smoother one.

C Stand-in: temperature to PWM mapping (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Simulate a room to compare controllers

A controller is easiest to judge by watching it work over time. The model below gives a room a heat source (a computer warming it by 0.15 C per step) and a fan that cools by an amount depending on its speed. The first run uses a single threshold (no hysteresis), the second uses two thresholds. Count how many times the fan switches.

C Stand-in: single threshold vs hysteresis (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The simulated room uses crude numbers, but the effect is real: the single-threshold controller switches the fan on most steps (60 times in 80), while hysteresis switches only 7 times.

Adding a simple filter and a safety rule

Raw readings jitter, so filter them (a moving average or exponential filter, as in the sensors lesson). Always add fail-safes: if the sensor returns an impossible value (below -20 C or above 100 C, or NaN), run the fan at a safe default and show an error, instead of switching it off. A cooling device that stops when its sensor breaks is the wrong failure mode.

C Stand-in: sensor validation (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Extensions

  1. Set the target with a potentiometer (map(analogRead(A1), 0, 1023, 20, 35)).
  2. Show temperature, target and fan percent on an LCD.
  3. Add a manual override button and an AUTO mode, using a state machine like the traffic light project.
  4. Use a PID controller (proportional, integral, derivative terms) for precise control of a heater: many Arduino libraries implement it.
  5. Make the readings non-blocking by replacing delay(1000) with millis() timing, so buttons stay responsive.
  6. Log the data with the data logger project.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What problem does hysteresis solve?

    Using different on and off thresholds creates a dead band where the previous state is kept, preventing chatter.
  2. 2. Why does the PWM mapping start at a minimum like 90 instead of 0?

    Below a certain duty cycle the torque is too small to overcome friction.
  3. 3. What should the controller do if the sensor returns NaN?

    A cooling system should fail safe. Running the fan while reporting the fault is safer than stopping it.
  4. 4. With ON_ABOVE = 28 and OFF_BELOW = 26, what does the fan do at 27 degrees?

    Between the thresholds the state does not change, which is the dead band.

Summary

  • A thermostat measures, compares and acts; hysteresis uses two thresholds to stop chatter.
  • Proportional control scales PWM speed with temperature, starting above the fan's minimum duty.
  • Simulate the environment to compare controllers and tune the thresholds before building.
  • Validate sensor data and fail safe.

Next: Arduino Practice Problems