I'm trying to control a 12 volt PC fan with an arduino and most things are fine until I try to shut it off.
I presume it's an issue with the code, but I'll add a diagram that shows the wiring too.
They have a common ground, the Board has 5 Volt while the fan gets 12 Volt and a 2N2222A Transistor with a 100 Ohm Resistor between Arduino and Transistor closes the circuit.
(Please roast my wiring and component selection after solving the issue, I've a few spare Nanos and other components. Unless I need a diode. Then I'll have to look for one tomorrow)
int DutyCycle = 0;
const int PwmPin = 3;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(PwmPin, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
if(Serial.available()>0){
Serial.print("Amount of bytes available: ");
Serial.println(Serial.available());
Serial.print("Next byte in buffer: ");
Serial.println(Serial.peek());
DutyCycle = Serial.parseInt();
Serial.print("Current Dutycycle: ");
Serial.println(DutyCycle);
analogWrite(PwmPin, DutyCycle);
if (DutyCycle == 0 ){
digitalWrite(PwmPin, LOW);
Serial.print(DutyCycle);
Serial.println(" was written to the analog pin");
}
while(Serial.available()>0){
int Throwaway = Serial.read();
Serial.print("Byte thrown away: 0b");
Serial.println(Throwaway, BIN);
}
}
delay(100);
}
The few random bits of code here and there were tries to either empty the serial buffer so Serial.available() didn't run when not needed or to get the motor to shut off.
It's from a project from over a year ago so I don't remember everything I did except adding pinMode and the second if clause and its contents.
So followed your advice and replaced the resistor (330Ω), transistor and added a kickback diode (SB160). Just in case I also replaced the board, though it (and the previous board) both have the old bootloader, in case that is important.
Behavior is still the same so I assume it's an issue with the code.
I can measure the Voltages if necessary, but I don't expect to discover the issue there.
Edit: if I enter 0 and stop the fan with my finger (I know, bad idea, but the diode's now here) it doesn't start spinning again until I change the Dutycycle.
Also, if I take the transistor out when at 0 and put it back in after, the fan doesn't spin up again
Wouldn't it be simple to write a simple sketch that just turns the motor on and off continously? Like a modified Blink sketch? Then you would know for sure.
Your serial code is really whacky. If the code is so old, why not just start over? It's not a complicated sketch.
The Schottky's what I got at the makerspace, so I took that one.
The transistor got warm and sometimes hot (before I realised I had it upside down) and the Fan is a Noctua NF-A9 and takes 0.1 Amp but I've multiple fans that I'll connect in parallel as my project progresses