# If statement with Serial.print

Hi! I have a pretty basic question about using the Serial.print with an if/else statement. I want to output a moisture value of 0 if the voltage reading is 5, but if the voltage is below 5 I want to use an equation to calculate moisture and print that value instead. I can’t seem to code this properly and either only get a moisture of 0 (for any voltage reading) or a calculated value (so a voltage reading of 5 does not give 0). The current iteration of my code is below, thank you!

void loop() {
//first sensor
int sensorVal = analogRead(sensorPin);
//prints time since program started
Serial.print("Time_1: “);
time = millis();
Serial.print(time);
// wait a second so as not to send massive amounts of data
Serial.print(”, Serial Value: “);
Serial.print(sensorVal);
float voltage = (sensorVal/1024.0)*5.0;
Serial.print(”, Volts: “);
Serial.print(voltage);
Serial.print(”, Moisture Content: ");
float moisture;
if(voltage == 5){
moisture = 0;
Serial.println(moisture);
} else {
moisture = ((voltage - 4.98)/-0.089);
Serial.println(moisture);
}

`````` if(voltage == 5)
``````

You really can not get an exact equality between a float and an constant.

Try

``````if(voltage >=4.99 && voltage<= 5.01)
``````

Try

Since 1023/1024.0 * 5.0 is 4.995, and voltage can never be higher than that, the && and upper limit test are unnecessary.

moisture = ((voltage - 4.98)/-0.089);

In addition to what has been said above, your formula already goes to zero at V=4.98, so you really want this to be your threshold anyway (assuming that you don't want negative moisture readings).

So "if (voltage >= 4.98) ... " is what you want.

Hi,
Have you looked at the map function?

https://www.arduino.cc/en/Reference/Map

Tom...