0

I'm trying to read the analog value of the light sensor and print its percentage but for unknown reasons I'm getting negative values when I'm printing the value.

void setup() {
 Serial.begin(9600);
}
void loop() {
 // Let's say 1002 is the analogValue
 int analogValue = (int) analogRead(0);
 // get the percentage
 int value = 100 * analogValue / 1023;
 Serial.println("~~~~~~~~~~~~~~~~~~~~~~~~~");
 Serial.println(analogValue); // print the analog value 0...1023
 Serial.println(100 * analogValue); // just for test
 Serial.println(value); // The percentage
 Serial.println("~~~~~~~~~~~~~~~~~~~~~~~~~");
 delay(500);
}

I don't know what's going in background, but I'm getting negative values when I try to print the percentage:

~~~~~~~~~~~~~~~~~~~~~~~~~
1002
-30772
-30
~~~~~~~~~~~~~~~~~~~~~~~~~
asked Jun 24, 2017 at 14:24
0

1 Answer 1

2

Max value for int is 32,767. But 100 * 1002 = 100,200. You are overflowing the int. Use unsigned long. Or float and cast to int when printing.

answered Jun 24, 2017 at 14:31
2
  • Simplest would be to replace 100 by 100L. Commented Jun 24, 2017 at 14:48
  • Yes, but OP would have to be sure to do that on both lines - the original calculation as well as the Serial.println line (even though it's "just for test"). Either way works, though. Commented Jun 24, 2017 at 14:54

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.