Simple code for controlling a fan isn't workinf

Hi, Any help much appreciated

I’m trying to make a temperature controller with a fan~ unsucessfully though
Ultimately im trying to make it a PI controller, but the simple on/off version isn’t working

Can anyone see any problems in the hardware/code that may be causing this?

Many Thanks,
H

float temp;

int tempPin = A0; //arduino pin used for temperature sensor
int tempMin = 25; // the temperature to start the fan
int tempMax = 40;
int fan = 6; // the pin where fan is connected
int fanSpeed ;

void setup() {
pinMode(fan, OUTPUT);
pinMode(tempPin, INPUT);
Serial.begin(9600);
}

void loop() {
  temp = analogRead(tempPin)*5/1024.0;
  temp = temp - 0.5;
  temp = temp / 0.01;
Serial.print ("Temperature: ");
Serial.println(temp);
Serial.print ("Fan Speed:");
Serial.println(fanSpeed); 
delay(1000); // delay in between reads for stability


if(temp <= tempMin)
{
  fanSpeed = 0; 
  analogWrite(fan, LOW);}

else if (temp >= tempMin) 
{
  fanSpeed = 255;
   analogWrite(fan, HIGH); // spin the fan at the fanSpeed speed
}}

"Isn't working" may not provide enough information to help us solve the problem.

What does "isn't working" really mean? The fan runs? Doesn't run? Doesn't seem to react to temp changes? The code doesn't run?

I react on two lines. You use LOW and HIGH trying to set fanspeed. Do You know how HIGH is defined? I don’t but it could be 1! Send 255 for full fanspeed.

if(temp <= tempMin)
{
  fanSpeed = 0; 
  analogWrite(fan, LOW);}

else if (temp >= tempMin) 
{
  fanSpeed = 255;
   analogWrite(fan, HIGH); // spin the fan at the fanSpeed speed
}

Easier would be:

if(temp <= tempMin)
{
   fanSpeed = 0; 
   analogWrite(fan, fanSpeed);
}
else
{
   fanSpeed = 255;
   analogWrite(fan, fanSpeed); // spin the fan at the fanSpeed speed
}

Your motor driver does not look right. The diode should be across the motor, banded end (cathode) to motor supply and the anode to the motor wire that connects to the transistor collector or drain.

4dfcf06e11b42e97c5b67bf746f0b866d90d5571.png

What transistor are you using?