Controlling a 5V fan

Hi,

I am using the following code to try to turn on a small fan when my cat trips a PIR sensor. Right now I am using a small 5V fan for testing. I have it bread-boarded up and the PIR and the LED are working fine. I'm just not too sure on how to hook up the fan. It has two wires red and black. I'm assuming I need a resistor (pullup, pulldown?). Sorry for the newbie question, any help would be greatly appreciated. :blush:

//cat sensor

int pirPin = 2;
int ledPin = 13; 
#define FAN_PIN 5
#define FAN_DELAY 2000 // shorter time for testing
//#define FAN_DELAY 180000  // to give the kitty time to do her business
#define FAN_RUN_TIME 180000  // to run the fan for a few minutes

void setup(){
 pinMode(pirPin, INPUT);
 pinMode(ledPin, HIGH);
 pinMode(FAN_PIN, ? );
delay (2000); // it takes the sensor 2 seconds to scan the area around it before it can detect infrared presence.
}

void loop(){
  int pirVal = digitalRead(pirPin);

  if(pirVal == LOW){ //was motion detected

  // LED Code
  digitalWrite(ledPin, HIGH);
  delay(1000);
  digitalWrite(ledPin, LOW);
  delay(1000);
  
  // Fan Code
    delay(FAN_DELAY);
    digitalWrite(FAN_PIN, ? );
    delay(FAN_RUN_TIME);
    digitalWrite(FAN_PIN, ? );
    
  }
  delay(2000);
  
  }

Have you determined how much current the fan draws? Even if it is less than 40mA it generally isn't a good idea to hook up motors directly to Arduino pins. You want to be using a transistor to switch the fan on and off.

Thank you for taking the time to help.

Less than 10 mA of draw.

Could you suggest a transistor and wiring setup?

Many thanks XD

2N2222

Fan.jpg

Thanks very much! :)

You should add a capacitor parallel to the motor to smooth it out, otherwise it may be choppy.