Return value of 0 if value is less than zero

Background: I am using an analog pressure sensor with a range from 0-100PSI returning voltage values .44v to 4.44v. It's open air (or 0 PSI) voltage on the signal pin is .47 volts. I have a function that subtracts that .47v (to make zero) and then multiplies it by 25 (25 PSI per volt). Due to signal noise or other factors, sometimes my function returns a negative number, which wreaks havoc on my math. I would like to return a value of 0 when my offset math returns a negative number, but I'm having a problem with it.

The code that I wrote that doesn't work:

double EngineOilPressure() {
//insert oil pressure code here
float voltage = reading * 5.0;
voltage /=1024.0;

Serial.print(voltage); Serial.println(" volts");

if (voltage-.47 < 0)
{
}
else
{
}

float pressureP = voltadj * 25;
return PSIToPascal(pressureP);
}

The error that I get is

dynamic_engine.pde: In function 'double EngineOilPressure()':
dynamic_engine.pde:41:23: error: 'voltadj' was not declared in this scope
Error compiling.

The code that works but sometimes returns a very wrong value:

double EngineOilPressure() {
float voltage = reading * 5.0;
voltage /=1024.0;

Serial.print(voltage); Serial.println(" volts");

float pressureP = (voltage - .47) * 25;
return PSIToPascal(pressureP);
}

The scope of each of the two different and unrelated voltadj variables that your code (as below) declares is limited to within its enclosing set of braces.

if (voltage-.47 < 0)
{
}
else
{
}

or perhaps

float voltadj = voltage < .47? 0 : voltage-.47;

or

float voltadj = constrain(voltage-0.47, 0.0, 5.0);

or

Also see max() and constrain() reference pages at arduino.cc.

Another method, though one that is quite cryptic to understand, would be:

float pressureP = voltage > 0.47 ? (voltage - 0.47) * 25 : 0;

That is known (by me at least) as an inline conditional. The ? acts as an if operator, and the : as an else. Basically it's saying:

Voltage is greater than 0.47
Is that true?
then subtract 0.47 and multiply by 25 and assign it
otherwise:
assign 0

The format is simply:

value = {condition} ? {true value or expression} : {false value or expression};

If can be quite useful when you want to conditionally calculate or assign something. @jwpat7 makes mention of a max() function above. That max() function can itself be written with this inline conditional format:

maxval = a > b ? a : b;

Or: If a is greater than b then assign a otherwise assign b.

• This is the one I ended up using, thank you! I love the simplicity. Mar 3 '16 at 4:45

The Arduino way is to use constrain

float pressureP = constrain ((voltage - 0.47) * 25 , 0 [The Maximum your code can handle]);

This will return the value ((voltage - 0.47) * 25) but never less than 0 and never more than The maximum you provide.