# Compare float between limit

Hi,

how to write correctly this condition ?

``````float temperature;
if (data.temperature >= -15.0 && data.temperature <= 50.0)
{Serial.println ("it is Ok"}
else
``````

What’s wrong with how you got it wrote?

Tested and working:

``````void setup()
{
Serial.begin(9600);
}

void loop()
{
// The random() function creates a integer value,
// to get all kind of numbers I use a division.
float temperature = ((float) random(1, 4000) - 2000.0) / (float) random( 1, 100);

Serial.print( "The temperatue is ");
int n = Serial.print( temperature);
for( int i=n; i<8; i++)
{
Serial.print( " ");
}
Serial.print( " (");

// ------------------------------------------------

if( temperature >= -15.0 && temperature <= 50.0)
{
Serial.print( "it is Ok");
}
else
{
}

// ------------------------------------------------

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

delay( 1000);
}
``````

Thank’s, I have another working solution.

``````  compareValueFloat = data.temperature * 10;
compareValue = round(compareValueFloat);
if (!compareValue >= -150 && !compareValue <= 500)
{
data.temperature = NULL;
}
``````

Why is there a exclamation before the `compareValue` in the condition ?

Sorry, I was wrong.
This is my code, but I’m sure there is a more elegant way to write this code, probably as suggested from @Koepel.

``````void LoRaInterface::sanityCheck(StructData &data)
{
compareValueFloat = data.temperature * 10;
compareValue = round(compareValueFloat);
if (compareValue >= -150 && compareValue <= 500)
{
}
else
{
data.temperature = NULL;
}

compareValueFloat = data.humidity * 10;
compareValue = round(compareValueFloat);
if (compareValue >= 0 && compareValue <= 1000)
{
}
else
{
data.humidity = NULL;
}

compareValueFloat = data.voltage * 10;
compareValue = round(compareValueFloat);
if (compareValue >= 0 && compareValue <= 60)
{
}
else
{
data.voltage = NULL;
}
}

``````

When writing code, it is better to make it as simple and as straightforward as possible.
To check if a float temperature is between certain values or outside a certain range, you can write that directly in code. The ‘C’ and ‘C++’ language is perfect for that.

This is how to put it in code. You may use ‘and’ and ‘or’ instead of && and ||

``````void LoRaInterface::sanityCheck(StructData &data)
{
if (data.temperature < -15.0 or data.temperature > 50.0)
{
data.temperature = 0.0;
}

...
``````

Thanks, it work fine. Grazie @Koepel

Are you trying to detect a bad sensor or wrong outside temperature ? What happens if it really gets colder than -15°C or hotter than 50°C (in direct sunlight) ?
I would check for -100 and +500 or so.

This sensor will run on Sicily, Italy, and temperature are never less - 10! According to Wikipedia: -15.2°C and 48.5°C Ok, I will change the limits. Thank’s

1 Like

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