Introduction
Most of the time when working with software algorithms, a very basic issue is managing various ranges of inputs and outputs and their conversions. For example, in electronics amplifiers, we find a scenario where amplifiers support various ranges of inputs: -10 to 10 volts, 4 to 20 mA, or 0 to 20mA. Often, the signal conditioning circuits accept only one type of input and does changes to it on the fly to convert it to the respective range of amplifier input. The problem we faced was – in software, when the application user expects the elctronics to operate under these various ranges, it is essential to have a common routine for converting an input from one range to another range which is understood by the signal conditioning device.
The following points cover the problem statement:
- In the existing software, we found that the range conversion was very tightly coupled to the kind of range expected; for example, for -10 to 10 volt, there was a different formula, for 4 to 20 mA, there was a different formula.
- This was being used in many places from where the input was applied or the acquired signal was being processed.
Background
Consider a very easy scenario of range conversion. For example, “Convert a range of 1 - 4 to 2 - 8”, which is too trivial to do, but when it comes to converting a range from “-0.75 – 1.95” to “-0.023 to 5”, developers start doing basic math. It is obvious that it is not as trivial as it seems. Hence we thought of coming up with a generic range conversion formula to adapt to any such subtle conversions with one line of code.
Using the code
The method of range conversion can be used in many places where proportional characteristics are considered between ranges. The function ConvertFrom_Range1_Input_To_Range2_Output
can be used as is in any class.
private double ConvertFrom_Range1_Input_To_Range2_Output(double _input_range_min,
double _input_range_max, double _output_range_min,
double _output_range_max, double _input_value_tobe_converted)
{
double diffOutputRange = Math.Abs((_output_range_max - _output_range_min));
double diffInputRange = Math.Abs((_input_range_max - _input_range_min));
double convFactor = (diffOutputRange / diffInputRange);
return (_output_range_min + (convFactor * (_input_value_tobe_converted - _input_range_min)));
}
double dblConv_maReading = ConvertFrom_Range1_Input_To_Range2_Output(-10,10,4,20,0)
The output of this would be 12mA.
Points of Interest
- This range conversion is restricted to ranges which are proportional/linear in nature.
- For non-linear range conversion, we can use other techniques like interpolation, look up table, etc.
- This code can be used in any language including C, C++, C# by making a few language specific changes.
History
This is the first article in this segment from me and I will make sure I keep posting more. Thanks to CodeProject for providing this wonderful platform and thanks to community users.