I'm trying to do something simple - convert analogue pin input (0 - 1023) to byte equivalent (0 - 255).
All variables declared as int.
I do this (i.e. input value x 255/1023) and all starts going strange at about value 130.
// read potentiometer pin
potValue = analogRead(potPin);
Serial.print("Pin Value: ");
Serial.println(potValue);
// pot pin value will be from 0 - 1023
// convert this to 0 - 255
result = potValue * 255/1023;
Serial.print("Result: ");
Serial.println(result);
Pin Value: 128
Result: 31
Pin Value: 131
Result: -31
If I replace the "255 / 1023" with 0.25, then all works fine
result = potValue * 0.25; //255 / 1023;
Pin Value: 215
Result: 53
Now I understand that intermidiate int calcs are treated as ints, which may cause a problem with 255/1023, but 0.25 is no more an int than 255/1023?
An int can represent any integer value between -32768 and +32767
Anything outside this range wraps around.
130*255/1023. Think about how that sum works.
130 * 255 = 33150
That's outside the amount that an int will store.
You should either use an "unsigned int" that can store between 0 and 65535, or a "long" which can store considerably more (we're talking billions here).
Is this behaviour (intermediate calcs being influenced by data type of variable) just Arduino, or is it C? Damn sure this has never happened to me in years of Java..?
davetapson:
Is this behaviour (intermediate calcs being influenced by data type of variable) just Arduino, or is it C? Damn sure this has never happened to me in years of Java..?
C/C++ have that issue everywhere... Just try this anywhere =)
int foo = 20;
int bar = 35;
float baz = 0.0;
baz = foo / bar;