Can't get negative number result?

I am trying to scale a PWM input and output a PWM signal to an DC gear motor.
The input comes from an RC receiver with a signal between 1000 and 2000.
I need to output a value from -255 to 255.
When I enter a value that should return a -255 I get a 4294967041 value. But the
top of the scale seems to work, and a value of 1500 returns a zero.
What am I missing?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
long x;
long in_min;
long in_max;
long out_min;
long out_max;



int main()	
{
	long map(long x, long in_min, long in_max, long out_min, long out_max);
	
	x=1000;
	in_min=1000;
	in_max=2000;
	out_min=-255;
	out_max=255;
  	return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
	

}
I don't think the problem is in the code you posted, at least it gives me -255.

I'd guess it's something to do with the fact you do not initialize values and your getting random memory value in your calculation.
closed account (48T7M4Gy)
The problem is long integer division. This overcomes it ...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# include <iostream>

int main()
{
    long x=2000;
    
    long in_min=1000;
    long in_max=2000;
    
    double range_of_input = in_max - in_min; // <--
    
    long out_min=-255;
    long out_max=255;
    
    long range_of_output = out_max - out_min;
    
    long output = out_min + (x - in_min)* range_of_output /range_of_input;
    
    std::cout << output;
    
}


x = 1000 -> output = -255
x = 1500 -> output = 0
x = 2000 -> output = 255
Thanks guys. That works good. Appreciate the help.
Topic archived. No new replies allowed.