Try Embedded

Fan thermostat (LM35)

Read an LM35 with the 1.1 V reference for tenth-degree steps, and switch a fan with hysteresis so it does not chatter.

Sensors · Beginner

In a real product: Server rack cooling (Telecom and networking): The fan switches with hysteresis to keep equipment cool without chattering.

The LM35 is the simplest temperature sensor to read: its output is 10 mV for every degree Celsius, so there is no formula to look up. The interesting parts are getting a fine reading out of a 10-bit ADC, and switching something on a threshold without it flickering on and off.

What you'll learn

  • Choosing the ADC reference: 5 V gives half-degree steps, the internal 1.1 V gives tenth-degree steps
  • Hysteresis: two thresholds instead of one
  • Switching a motor from a pin with a transistor and a flyback diode

How it works

With the default 5 V reference, one ADC step is 4.9 mV, half a degree. analogReference(INTERNAL) switches the Uno's ADC to its internal 1.1 V reference, so a step is 1.07 mV, about a tenth of a degree, for temperatures up to 110 °C.

A single threshold at 30 °C would switch the fan on and off with every tenth of a degree of noise around it. Instead the fan turns on above 30 °C and off only below 28 °C: between the two it keeps doing what it was doing. That is a two-state machine, and the gap between the thresholds is the hysteresis.

The fan is a DC motor, which needs far more current than a pin gives. Pin 9 drives an NPN transistor's base through a 1 kΩ resistor; the transistor switches the motor's low side, and a diode across the motor takes the kick when it turns off.

Try this

  • Click the LM35 and set 29 °C, then 31, then 29 again: the fan stays on until you go below 28.
  • Remove analogReference(INTERNAL) and change 1.1 to 5.0: the readings now move in half degrees.
  • Make the fan's speed follow the temperature with analogWrite instead of switching it.

sketch.ino

// An LM35 on A0, read against the 1.1 V internal reference, switches a fan on above 30 C and off below 28 C.
const int FAN = 9;
const float ON_ABOVE = 30.0, OFF_BELOW = 28.0;
bool fanOn = false;

void setup() {
  Serial.begin(9600);
  analogReference(INTERNAL);  // 1.1 V full scale: about 0.1 C a step
  analogRead(A0);             // the first reading after changing the reference is discarded
  pinMode(FAN, OUTPUT);
}

void loop() {
  long sum = 0;
  for (int i = 0; i < 16; i++) sum += analogRead(A0);
  float celsius = sum / 16.0 * 1.1 / 1023 * 100;
  if (!fanOn && celsius > ON_ABOVE) fanOn = true;
  else if (fanOn && celsius < OFF_BELOW) fanOn = false;
  digitalWrite(FAN, fanOn);
  Serial.print(celsius, 1);
  Serial.print(" C, fan ");
  Serial.println(fanOn ? "on" : "off");
  delay(500);
}

Lessons behind it