I have an analog device mapped to a5 ( moisture sensor)
the raw analog values range from 110 to 1023
I'd like to display this as a percentage ( I believe the formula i have is correct , as tested in excel and attached)
The percentage value displayed is either 100 or 0
Raw value 1023 = 100% , anything less is zero
How .. why ?!? .. Help !
int analogPin = A5;
int sensorValue;
int percentValue;
void setup() {
Serial.begin(57600); // initialize the seri strip.begin();
}
void loop() {
sensorValue = analogRead(analogPin);
delay(500);
Serial.print(sensorValue);
Serial.print(" ");
percentValue = ((sensorValue-110)/(1023-110))*100; // Min analog val 110 , Max analog Value 1023. Range these as percentage
Serial.print(" ");
Serial.println(percentValue);
}
what fundamental issue have I not grasped here then ?
You've not grasped the fact that if you divide an integer by an integer, you get an integer result.
e.g. 99 / 100 = 0, because 100 goes into 99 zero times.
what fundamental issue have I not grasped here then ?
You also (in addition to the other comment) need to remember that percent is actually the answer * 100 In the other example, (which would require float to calculate) 99/100 = 0.99 so to get "percent" you multiply that by 100. If you multiply the numerator by 100 before doing the integer division, you get an integer percentage (I have shot myself in the foot with that one before).