 # Getting percentage from soil Sensor

I am trying to get the percentage humidity from a soil sensor, but I get 0 every time I try to convert the number from the output to a percentage. What am I doing wrong?

This is what I have right now and I get 0:

#include <LiquidCrystal.h>
LiquidCrystal lcd(8,9,4,5,6,7);
void setup() {
lcd.begin(16, 2);
}
void loop() {
lcd.setCursor(1,0);
lcd.print(“Soil Moisture”);
lcd.setCursor(3,1);
delay(3000); //change delay to change refresh rate
lcd.setCursor(3,1);
lcd.clear();
}

If I change this line: lcd.print(int(analogRead(A1)/1024*100)); to this: lcd.print(analogRead(A1)); I get proper numbers between 0 and 1023. I have tried with and without the int() function.

`````` lcd.print((analogRead(A1)*100L)/1024);
``````

Thank you. But why do I have to do it that way? If I divide by 1024 then multiply by 100 I get the same if I multiply by 100 then divide by 1024.

Edit: I know now. When I divide the number first it is less than one, or rounded to 0, then when I multiply by 100 it is 100*0 so that is what I get.

mAineAc: Thank you. But why do I have to do it that way? If I divide by 1024 then multiply by 100 I get the same if I multiply by 100 then divide by 1024.

On paper with a human doing the calculation. In a computer things are a little different. With integer math, the result is always an integer. So 1023 / 1024 == 0. Multiply 0 * 100 and you get 0.

1023 / 1024 == 0 0 * 100 == 0

1023 * 100UL == 102300 102300 / 1024 == 99

What does the L after the 100 do?

mAineAc: What does the L after the 100 do?

When you just write a number smaller than 32,767 the compiler treats it as a 16 bit int. If you did the math with 16 bit ints then it looks like this...

1023 * 100 == -28771

but

1023 * 100L == 102300

with 32 bit numbers it doesn't overflow.

The L says, treat this number as a 32 bit long. With a long you can have bigger numbers so things don't overflow.