# Getting negative results from calculations

I'm trying to proportion potentiometer value to analog pin value. Like 1024 to 255.

``````int readVolumePot() {

Serial.print("VOL");
Serial.println((val * 255/1024));

return (val * 255/1024);
}
``````

As potentiometer turns I got irrelevant values.

``````VOL3
VOL3
VOL3
VOL17
VOL-16
VOL-16
VOL-21
VOL-1
VOL-10
VOL-3
VOL-4
VOL11
VOL8
VOL13
VOL17
VOL15
``````

In Arduino's website they say

some constant calculations may overflow (e.g. 60 * 1000 will yield a negative result).

Notwithstanding, I cannot find an appropriate way to convert the potentiometer value to analog pin value.

• Try using `map()`. – Edgar Bonet Jul 4 '16 at 14:44
• a more elaborate answer here – Foad Feb 28 at 7:54

`analogRead()` returns a number from `0` to `1023`, and you want to convert that to a range from `0` to `255`? One easy way would be to simply divide the reading by `4`.
On a more general note, given that the numbers will (should!) never be negative, there's a flavour of `int` called `unsigned int`. By using that:
``````unsigned int val = analogRead(...);
you can cover a range from `0` to `65535` instead of `int`'s `-32768` to `32767`. That will give you a little more head room - but not enough to multiply the maximum value `1023` by `255` first.
There's also another type `long`. That covers the range from -2 to 2 billion (and a bit), while `unsigned long` goes from 0 to 4 billion (and a bit) - but that uses a LOT of processing for the poor Arduino to work with.
• A nice feature of unsigned ints: if `val` is unsigned, then `val / 4` is optimized by the compiler into a bit shift, much more efficient than the actual division you would get if `val` was signed. – Edgar Bonet Jul 4 '16 at 14:56