DEV Community

Walter Chen
Walter Chen

Posted on Fully Autonomous

4–20 mA scaling in JavaScript: keep the number separate from the signal status

A 4–20 mA input is a small example of why a valid number and a valid measurement are different things.

Suppose a transmitter maps 0–10 bar onto 4–20 mA. The normalized signal is:

fraction = (currentMa - 4) / 16

Then:

value = lower + fraction * (upper - lower)

At 12 mA, the fraction is 0.5 and the result is 5 bar. The arithmetic is straightforward. The interface decisions deserve more care.

Preserve the input before formatting the result

Here is a small standalone JavaScript example. It keeps the calculated value separate from an out-of-span flag:

function scaleCurrent(currentMa, lower, upper) {
  if (![currentMa, lower, upper].every(Number.isFinite)) {
    throw new TypeError("Finite numeric inputs required");
  }
  if (upper === lower) {
    throw new RangeError("Range endpoints must differ");
  }

  const fraction = (currentMa - 4) / 16;
  return {
    value: lower + fraction * (upper - lower),
    outsideNominalSpan: currentMa < 4 || currentMa > 20
  };
}
Enter fullscreen mode Exit fullscreen mode

This deliberately accepts reversed engineering endpoints: a 100–0 range gives 50 at 12 mA. It rejects non-numeric values rather than silently coercing an empty field to zero. A form layer should parse and validate its text inputs before calling it.

Five checks worth keeping

Current Range Calculated value Outside 4–20 mA?
4 mA 0–10 bar 0 bar No
12 mA 0–10 bar 5 bar No
20 mA 0–10 bar 10 bar No
3.6 mA 0–10 bar −0.25 bar Yes
12 mA 100–0 units 50 units No

The last two rows catch different mistakes: assuming that every range is ascending, and confusing an extrapolated number with an accepted process reading. The example function and these five cases were executed during preparation.

Do not hide diagnostics by clamping

If a display clamps −0.25 bar to zero, the user loses evidence that the input was outside the nominal span. Keep the raw input, calculated value, units and status visible. Device-specific fault-current thresholds belong in a separate, explicitly configured layer; “outside 4–20 mA” alone does not diagnose a broken sensor.

Likewise, these calculations do not model ADC quantization, resistor tolerance, transmitter accuracy or the voltage available at the instrument. Those need their own assumptions.

For an interactive companion, the SensorCatalog 4–20 mA converter lets readers explore signal scaling without installing anything.

Disclosure: this article and its standalone code example were prepared with AI. Walter Chen maintains SensorCatalog and is affiliated with the linked resource. The site contains advertising and sensor-inquiry links to SensorSpan. This is a calculation example, not a calibration record or installation approval.

Top comments (0)