ABC of Electronics cosycom.com
EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 48

Project: Temperature-Controlled Fan

A closed feedback loop.

Read a temperature sensor, then set the fan speed with PWM. A simple rule: below 25 degrees fan off, above 40 degrees full speed, and a straight line between.

Add a small hysteresis band so the fan does not rapidly turn on and off around a threshold. Drive the fan through a transistor with a protection diode.

This is the basic pattern behind thermostats and many other controllers.

EXAMPLE
uint8_t fan_duty(int t) {          /* t in degrees C */
    if (t <= 25) return 0;
    if (t >= 40) return 255;
    return (uint8_t)((t - 25) * 255 / 15);
}