Understanding why float is returning specific number

I have a moisture sensor and was trying to return a percentage back until I discovered the map command.

That being said, as I was dealing with int and floats, I have not been able to see the value I am expecting to be returned if I just do simple division.

Can you please help me understand what I am doing wrong?

int val1;
float val2;
float outputVal;

val1 = analogRead(A0);
val2 = 4095;

outputVal = val1/val2;

My Particle.variable result is this: “result”: 6.152402546588351e-270,

What is happening here?!

Two things:

val/val2 will give you a percentage value, but in the range of 0-1, not 0-100 if that’s what you were expecting. The code below gets you 0-100.

The main thing is that Particle.variable takes a double (8-byte floating point) not a float (4-byte floating point). I’m surprised that compiled, but I tried it and it does and results in a very, very small value because of the extra “garbage” bytes.

double pct;

void setup() {
    Serial.begin(9600);
    Particle.variable("pct", pct);
}

void loop() {

    pct = (analogRead(A0) * 100.0) / 4095.0;
    Serial.printlnf("pct=%lf", pct);

    delay(5000);
}
1 Like

@rickkas7 is spot on.

There also was a discussion about this already, which woild have popped up via a forum search
Oddities with Particle.publish() and float
Particle.publish() a float variable

@rickkas7 - Thanks for the quick response!

@ScruffR - Thanks and quite truthfully, I searched like crazy on this before posting.

I didn’t search though on it being a problem with Particle.publish or Particle.variable since it was actually “working”.

Thanks for the help on this!

In cases like this Serial.print()ing your variables is a good way to see where the actual problem is.