Having problems with maping temperature to fan speed

So i am trying to make the fan speed change with the temperature, i mapped the temperature readings from 50-100 celsius to 50-255 into fanSpeed pwm, the code works fine in the ranges 50-100 celsius, but when it goes below 50 instead of fanSpeed going to 0 by the if function i wrote it goes below 50 and at around 30 celsius it goes into negative values and if i set unsigned int it overflows and goes to 65500, any idea how to fix this and why the if functions aren't working?, in the void loop i'm just calling the void fan

code:

void fan() //loop for automatic fan speed temperature control
{
    pinMode(fanPin, OUTPUT); //sets fanPin as output

    if (currentTemperature < 50)
    {
        fanSpeed = 0;
    }
    if (currentTemperature > 100)
    {
        fanSpeed = 255;
    }
    else
    {
        fanSpeed = map(currentTemperature, 50, 100, 50, 255); //maps currentTemperature from 50-100 to 50-255 for automatic variable fan speed control and it saves the value to fanSpeed
    }
    analogWrite(fanPin, fanSpeed); //outputs fanSpeed value(0-255) to fanPin
}

missing an else after the first if ?

  if (currentTemperature < 50) fanSpeed = 0;
  else if (currentTemperature > 100) fanSpeed = 255;
  else fanSpeed = map(currentTemperature, 50, 100, 50, 255); // here we know we are between 50 and 100 she the mapping will work

Are you looking for the constrain() function?
Leo..

Hello
check this untested sketch for your fan speed project.

void fan() //loop for automatic fan speed temperature control
{
  pinMode(fanPin, OUTPUT); //sets fanPin as output
  switch (constrain(currentTemperature, 50, 100) {
  case 50: fanSpeed = 0;
    break;
  case 100: fanSpeed = 255;
    break;
  default:  fanSpeed = map(currentTemperature, 50, 100, 50, 255);
  break;
  }
  analogWrite(fanPin, fanSpeed); //outputs fanSpeed value(0-255) to fanPin
}

Ultimately constrain worked, thanks for all the answers btw

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.