Switching a Fan (MOSFET Driver)
Optional practice: switch a fan on and off through a MOSFET, set its speed with PWM, give it a soft start, and add a thermostat that does not flicker on and off.
Optional practice: a fan on the virtual Uno
This practice is optional. Do it if you have time. Nothing in class depends on it.
The virtual board has a DC fan switched by a logic-level MOSFET on D9, wired like the lesson. The pin only drives the MOSFET's gate - the fan's current comes from its own supply. So the code is exactly what you would write for an LED on D9:
digitalWrite(fanPin, HIGH)turns the fan on at full power,LOWturns it offanalogWrite(fanPin, 0 to 255)sets the speed with PWM, as in Lesson 15
What the simulator does not model: the external supply, the gate resistors, the flyback diode, a MOSFET getting hot, or a fan that will not start at low PWM. Those are what the bench is for.
The lesson's sketch
Press Run and watch the fan speed up from off to full, stop for a second, then start again.
- Each step of the loop raises the power by 1 and waits 10 ms, so the ramp takes about 2.5 s.
- A real fan may not start turning until the PWM value is quite high. That is normal.
Fan on, fan off
Turn the fan on for 2 seconds, then off for 1 second, over and over.
Use digitalWrite - on is HIGH, off is LOW.
Half speed, then full speed
Now set the speed with analogWrite. Each time round loop():
- run the fan at half power (128) for 2 seconds
- then at full power (255) for 2 seconds
- then off (0) for 1 second
Soft start, then hold
Starting a fan at full power all at once pulls a big surge of current. A soft start brings the power up in small steps instead.
Each time round loop():
- use a
forloop to raise the power from 0 to 255, one step at a time, waiting 10 ms after each step - hold full power for 2 seconds
- then turn the fan off for 1 second
It is the lesson's sketch with a 2 second hold added.
A thermostat that does not flicker
The board now has a temperature sensor on A0 (move its slider while the sketch runs). Switch the fan on when the room is hot.
A single switch point causes trouble: if the fan turns on above 600 and off below 600, a reading that wobbles around 600 switches the fan on and off many times a second. The fix is a gap between the two switch points, called hysteresis:
- reading above 600: fan on (
HIGH) - reading below 500: fan off (
LOW) - in between: do nothing - the fan stays as it was
Read the sensor every 50 ms. The test warms the room up, lets it cool a little, cools it right down, then warms it again - and checks the fan only changes at the right points.
Try it on a real Uno
Build the MOSFET fan circuit from Lesson 16 - gate resistor, pull-down, flyback diode and common GND - and upload Half speed, then full speed. Measure VDS at full power: well under 1 V means the MOSFET is fully on.
For the thermostat, a potentiometer on A0 stands in for the temperature sensor, as in the lesson's challenge.