DEV Community

Cover image for Don’t Let Raw Sensor Counts Leak Into Control Logic
blessed Jegbefumwen
blessed Jegbefumwen

Posted on

Don’t Let Raw Sensor Counts Leak Into Control Logic

A control program often receives values that do not look like the quantities an operator understands.

An analogue input might arrive as an integer count from an input module. The display, alarm logic and sequence code may each convert that count differently. Over time, one part of the project uses raw counts, another uses engineering units, and a third relies on a hard-coded threshold whose meaning is unclear.

A better pattern is to convert and validate the measurement at the boundary of the application. Downstream logic should work with named values in engineering units, not unexplained integers.

This example uses Python to demonstrate the pattern. It is for learning and testing; it is not a substitute for configuring, checking or commissioning a real PLC analogue input.

Convert once, near the input

Suppose a module reports an integer count that represents a pressure transmitter’s measurement range. The conversion should be explicit about the raw range and engineering range.

from dataclasses import dataclass

@dataclass(frozen=True)
class ScaledValue:
    value: float
    units: str

def scale_linear(raw: int, raw_min: int, raw_max: int,
                 eng_min: float, eng_max: float) -> float:
    if raw_max <= raw_min:
        raise ValueError("raw_max must be greater than raw_min")

    if not raw_min <= raw <= raw_max:
        raise ValueError("raw input is outside the configured range")

    fraction = (raw - raw_min) / (raw_max - raw_min)
    return eng_min + fraction * (eng_max - eng_min)
Enter fullscreen mode Exit fullscreen mode

For example, if the configured input range maps to 0–10 bar, the application can convert the raw reading into a pressure value:

raw_count = 12000

pressure_bar = scale_linear(
    raw=raw_count,
    raw_min=4000,
    raw_max=20000,
    eng_min=0.0,
    eng_max=10.0,
)

pressure = ScaledValue(value=pressure_bar, units="bar")
print(pressure)
Enter fullscreen mode Exit fullscreen mode

The numbers here are illustrative. Actual raw counts, signal types and engineering ranges must come from the specific hardware configuration and instrument documentation.

The benefit is not the formula itself. It is having one clearly defined place where the conversion happens.

Separate scaling from measurement quality

A number can be within the configured range and still be unusable. The input may be stale, the channel may report a fault, or the transmitter may be disconnected.

Represent quality separately from the value:

from enum import Enum, auto

class Quality(Enum):
    GOOD = auto()
    BAD = auto()
    STALE = auto()

@dataclass(frozen=True)
class Measurement:
    value: float | None
    units: str
    quality: Quality
Enter fullscreen mode Exit fullscreen mode

A downstream function can then refuse to use an invalid measurement rather than treating a fallback number as real:

def is_pressure_high(measurement: Measurement, limit_bar: float) -> bool:
    if measurement.quality is not Quality.GOOD:
        return False

    if measurement.value is None:
        return False

    return measurement.value > limit_bar
Enter fullscreen mode Exit fullscreen mode

In an actual control application, “return False” may not be the right response to bad quality. The correct behaviour depends on the process and the designed response to instrument failure. The key point is to make bad quality explicit and handle it deliberately.

Keep units visible in names and interfaces

A threshold such as 7.5 is difficult to interpret without context. Is it bar, metres, degrees, or a raw count?

Names can help:

HIGH_PRESSURE_LIMIT_BAR = 7.5
Enter fullscreen mode Exit fullscreen mode

For larger systems, measurement objects or strongly typed interfaces can make it harder to accidentally compare unrelated quantities. Even a simple convention—include units in variable names and document the source range—can prevent confusion during maintenance.

Avoid converting the same signal independently in multiple places. If the display uses one conversion and the alarm uses another, the operator may see a value that does not match the logic driving the alarm.

Test boundaries, not just typical readings

A scaling function should be checked at its endpoints, in the middle, and outside the configured range.

def test_scale_endpoints_and_midpoint():
    assert scale_linear(4000, 4000, 20000, 0.0, 10.0) == 0.0
    assert scale_linear(12000, 4000, 20000, 0.0, 10.0) == 5.0
    assert scale_linear(20000, 4000, 20000, 0.0, 10.0) == 10.0

def test_out_of_range_input_is_rejected():
    try:
        scale_linear(25000, 4000, 20000, 0.0, 10.0)
    except ValueError:
        return

    raise AssertionError("out-of-range input should be rejected")
Enter fullscreen mode Exit fullscreen mode

Also test configuration errors, invalid quality, and any raw values that the hardware uses to indicate an open circuit or channel fault. Those details vary by module and signal configuration, so they should not be guessed from a generic example.

Don’t silently clamp unexpected values

It may seem convenient to clamp a raw value to the configured range. But clamping can turn an invalid reading into a plausible-looking measurement.

For instance, an unexpectedly high raw count could become “10 bar” after clamping. A display might then show a valid endpoint even though the input indicates a wiring, configuration or hardware problem.

Clamping can be appropriate for some applications, but it should be a documented design decision—not an automatic way to hide out-of-range data. In many cases, preserving a bad-quality status is more informative.

Make configuration reviewable

Scaling parameters are part of the interface between instrumentation and application logic. They should be traceable to the configured channel and instrument range.

A reviewable setup records, at minimum:

  • The input channel and signal type
  • The raw range expected from the module
  • The instrument’s engineering range and units
  • How out-of-range or fault values are handled
  • Where the scaled value is consumed

The exact documentation process depends on the project. The practical goal is that another engineer can establish why a raw value becomes a particular engineering value without searching through unrelated logic.

Conclusion

Analogue scaling is a small piece of code with a large effect on everything that uses the measurement. Convert the input once, keep units visible, represent quality separately, and test the boundaries.

Most importantly, do not let a plausible number hide an invalid signal. Control logic is easier to review and maintain when every value has a clear unit, source and quality status.

Top comments (0)