Math issue inverting the value of a slide potentiometer

I am trying to first invert the value given to me off of an analog read on a slide potentiometer and then generate a percentage of the value. When I say invert I mean 0 = 1024 (the highest value) and 1024=0.

To do so the math is simply do (0-x)+1024 where x is the value of the potentiometer.

Then to generate the percentage the equation would be (x*100)/1024 where x is the value of the potentiometer. The problem is that when I do the *100 part, everything goes haywire. I end up with very random values. For example the the meter could be at 600 value and I end up with -25,000. For the life of me I can't figure out why this is happening. Below is my code with each mathematical step on a separate line.

// Pin definitions
#define SLIDER1  0

void setup(){
  Serial.begin(9600);
  
}

void loop(){
  int slide1 = calcSlide(analogRead(SLIDER1));
  //Serial.println(analogRead(SLIDER1));
  Serial.println("-------------");
  delay(1000);
}

int calcSlide(int val){
  Serial.print("val=");
  Serial.println(val);
  val = 0-val;
  Serial.print("0-val=");
  Serial.println(val);
  val = val+1024;
  Serial.print("val+1023=");
  Serial.println(val);
  val = val*100;
  Serial.print("val*100=");
  Serial.println(val);
  val = val / 1024;
  Serial.print("val / 1023=");
  Serial.println(val);
}

The first part, inverting the analog input reading might best be done using the Arduino map function:

int slide1 = map(analogRead(slider1),0,1023,1023,0);

1024-x is the more standard way to write (0-x)+1024. Additionally, the maximum value for an int is 32,767 so multiplying anything larger than 327 by 100 will result in an overflow error. Declare val as long.

Thanks mapping was a much better way of doing what I was trying to do and when I set everything to long (even the initial analogRead) the math started working. There is apparently no error when you have an int variable greater than 32,767. It just gives you a strange number instead.

davejlong:
Thanks mapping was a much better way of doing what I was trying to do and when I set everything to long (even the initial analogRead) the math started working. There is apparently no error when you have an int variable greater than 32,767. It just gives you a strange number instead.

There is apparently no error when you have an int variable greater than 32,767. It just gives you a strange number instead.

Between variables overflowing and automatic sign extension, signed variables can bite you at times, especially when mixing types in an expression. Just using unsigned variables can prevent lots of problems sometimes.

Lefty

To generate percentages directly you can use the map function

p = map(analogRead(SLIDER1), 0,1023, 100, 0);

or do

p = (10230 - analogRead(SLIDER1)*10) /102; // the multiply by 10 takes care of rounding errors. 10230/102 = 100 where 1023/10 = 102