Conversion of the real voltage value to the number

Hi, I am a new learner and I have a big issue with the comparison operation of numbers. For example, If the code is following like this,

if (x> 120) digitalWrite(LEDpin, HIGH);

What I don't understand is calculating out the value 120. How can I know whether 5V is equal to which number? 120 or 8 or some number?

Thanks all.

You haven't posted your complete sketch so I have no idea where the value in "x" comes from.

If "x" is the value obtained from analogRead() then it will be a number proportional to the voltage on the Analog Pin. For example if the voltage on the pin is 5V x will be 1023. If it is 0v x will be 0. If it is 3.7v x will be 1023 / 5 * 3.7 or 757 (approx).


in a standard UNO 0V equals 0 and 5V equals 1023

that means every step = 5V/1023 ~4.8...milliVolts

If you want a led light up if the voltage is above 2 Volt you can calculate the analogRead() value expected 2Volt / 4.8... milliVolt = ~ 409

if (analogRead(A0) > 409) digitalWrite(led, HIGH);
else digitalWrite(led, LOW);

or you can work with the voltages in your program

float raw = analogRead(A0);
float voltage = raw * 5.0 / 1023;

if ( voltage > 2.0 ) digitalWrite(led, HIGH);
else digitalWrite(led, LOW);

hope this helps

Thanks you very much Robin2 and robtillaart. You guys had helped me a lots. Now I have an understanding about it. I appreciate your help.