Create Tolerance In A Variable

I am trying to write a piece of code in a way as to give the if statement a lower tolerance. Im not sure what i should be searching for. If anyone could shed some light it would be greatly appreciated.

``````output = map(average, 10, 1023, 0, 99);

if(humidity) < output){  // what i want to do here is give the function a lower tolerance so if output =50 i can use 45- 55 instead.
digitalWrite(fan, HIGH);
delay(500);
digitalWrite(fan, LOW);
}
``````
``````if((humidity =< output+5) || (humidity => output-5))
``````

Something like that. Untested!

if(humidity >= output -5 && humidity <= output + 5)?

It’s not clear what you want to do.

Do you mean “run the fan when the humidity is within 5 points of the specified value”? That would be:

``````if (humidity >= output - 5 && humidity <= output + 5)
``````

Do you mean “run the fan when the humidity is NOT within 5 points of the specified value”? That would be:

``````if (humidity < output - 5 || humidity > output + 5)
``````

Sorry, I want the fan to run.

Thank you all, It's sorted.

Much appreciated!

If you want to know when two values are within a certain tolerance of each other you can subtract them and use abs() to get the absolute difference between them. E.g.:

``````if(abs(target-actual) < tolerance)
{
// target and actual are close
}
else
{
// target and actual are not close
}
``````

If you are trying to apply hysteresis instead, you can do that using a pair of if/else statements to compare the value to two different thresholds.