PLC Program to Convert Analog Input to Engineering Units
ScaledValue = (RawValue / MaxRaw) * MaxEngineeringValue to get the engineering units.Examples
How to Think About It
Algorithm
Code
VAR RawValue : INT; (* Raw analog input from ADC *) ScaledValue : REAL; (* Converted engineering unit value *) MaxRaw : INT := 4095; (* Max ADC value for 12-bit input *) MaxEng : REAL := 100.0; (* Max engineering unit, e.g., 100 degrees *) END_VAR RawValue := AI_Channel; (* Assume AI_Channel is the analog input tag *) ScaledValue := (REAL(RawValue) / REAL(MaxRaw)) * MaxEng; (* Output the scaled value *) Print('Scaled Value: ' + REAL_TO_STRING(ScaledValue));
Dry Run
Let's trace RawValue = 2048 through the code
Read Raw Input
RawValue = 2048
Calculate Scaled Value
ScaledValue = (2048 / 4095) * 100 = 50.0
Output Result
Print 'Scaled Value: 50.0'
| RawValue | ScaledValue |
|---|---|
| 2048 | 50.0 |
Why This Works
Step 1: Reading Raw Input
The PLC reads the analog input as a raw integer value from the ADC, which represents the signal strength.
Step 2: Scaling Calculation
The raw value is divided by the maximum raw value to get a fraction, then multiplied by the maximum engineering unit to convert it.
Step 3: Output the Scaled Value
The scaled value is now in real-world units and can be used for control or display.
Alternative Approaches
VAR RawValue : INT; ScaledValue : REAL; LookupTable : ARRAY[0..4] OF REAL := [0.0, 25.0, 50.0, 75.0, 100.0]; Index : INT; END_VAR RawValue := AI_Channel; Index := RawValue / 819; (* 4095/5 approx 819 *) ScaledValue := LookupTable[Index]; Print('Scaled Value: ' + REAL_TO_STRING(ScaledValue));
VAR RawValue : INT; ScaledValue : REAL; RawLow : INT := 0; RawHigh : INT := 4095; EngLow : REAL := 0.0; EngHigh : REAL := 100.0; END_VAR RawValue := AI_Channel; ScaledValue := EngLow + (REAL(RawValue - RawLow) * (EngHigh - EngLow) / REAL(RawHigh - RawLow)); Print('Scaled Value: ' + REAL_TO_STRING(ScaledValue));
Complexity: O(1) time, O(1) space
Time Complexity
The scaling calculation is a simple arithmetic operation done once per input read, so it runs in constant time O(1).
Space Complexity
Only a few variables are used for calculation, so space complexity is O(1).
Which Approach is Fastest?
Direct formula scaling is fastest and simplest; lookup tables add overhead but can speed up repeated conversions with fixed ranges.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct Formula Scaling | O(1) | O(1) | Simple, precise scaling |
| Lookup Table Scaling | O(1) | O(n) | Fast conversion with fixed steps |
| Linear Interpolation | O(1) | O(1) | Flexible range scaling |