I have a lever/joystick that can be pulled manually, which gives a value range between (0 to 250) depending on the percentage of how much it has been pulled. This serves as my input to the C code. The C code should give a proportional value of current as the output in the range of 0 to 2000 mA. For eg.: 0 pull of joystick gives 0mA current, 250(max) pull of joystick gives 2000mA current as output, and the between values porportionally. I am unable to figure out how to design such a code in C. I was thinking maybe the code should use an equation y=mx c, for getting continuous proportional outputs for the real time inputs. Please can someone help me with this?
CodePudding user response:
Given the input and output ranges, this code calculates the scaling factor (m) and offset (c) for a linear equation that can calculate a proportional output from an input. This code works even when the minimum range is nonzero.
You may need to adjust the variable types and for rounding issues to suit the needs of your application.
int const input_min = 0;
int const input_max = 250;
int const output_min = 0;
int const output_max = 2000;
float scaling_factor_m = (float)(output_max - output_min) / (input_max - input_min);
float offset_c = (output_min - (input_min * scaling_factor_m));
int input_value_x = InputGetValue(); // From ADC or whatever
int output_value_y = (int)((input_value_x * scaling_factor_m) offset_c);