What this article answers
Article summary
A 1D Kalman Filter in IEC 61131-3 Structured Text estimates the true process value from noisy sensor data by updating state, gain, and covariance each scan. Compared with a standard low-pass filter, it can reduce variance while preserving faster tracking, which matters when PID loops, alarms, or interlocks cannot tolerate avoidable phase lag.
Noisy process data is not a programming inconvenience; it is a control problem. Ultrasonic level sensors, load cells, pressure transmitters, and flow meters all produce measurement noise under ordinary plant conditions because vibration, EMI, turbulence, entrained air, and mounting realities do not politely disappear for the sake of a clean trend.
Ampergon Vallis metric: In bench testing inside the OLLA Lab Signal Simulator, a first-order lag filter applied to a noisy level signal produced approximately 400 ms of response delay, while a 1D Kalman Filter implemented in Structured Text tracked the same underlying waveform with about 45 ms delay at comparable visual smoothness. Methodology: 12 simulated test runs, single-sensor level-tracking task, first-order lag baseline comparator, 3/2026 bench window. This supports the practical claim that predictive estimation can preserve responsiveness better than simple smoothing in this test condition. It does not prove universal superiority across all sensors, scan times, or tuning choices.
The engineering point is simple: if your PID loop is chasing noise, a low-pass filter may calm the trend while quietly degrading control response. Valves and dampers usually notice before the meeting does.
Why is Structured Text superior to Ladder Logic for Kalman filtering?
Structured Text is the correct IEC 61131-3 language for this class of algorithm because Kalman filtering is iterative math with retained state, not rung-centric interlock logic. You can force the equations into Ladder Diagram, but “possible” is not the same as “sane.”
Structured Text fits the algorithm more cleanly for three reasons
- Execution clarity: ST expresses algebraic operations directly. The predict-update sequence reads in the same order as the underlying equations.
- State retention: A Kalman filter must carry prior estimate values from one scan to the next, including previous covariance and previous state estimate. ST handles this naturally with retained variables.
- Auditability: In LD, the same filter often becomes a chain of `ADD`, `SUB`, `MUL`, and `DIV` blocks spread across multiple networks. That is harder to review, harder to maintain, and easier to break during edits.
- Scan-cycle discipline: Complex floating-point math in LD can increase visual and execution overhead. The issue is not that PLCs cannot do math; they can. The issue is that LD is a poor place to hide a small numerical method.
The practical distinction is syntax versus deployability
Ladder Logic is excellent for permissives, sequences, interlocks, and discrete control visibility. It is not the best medium for compact numerical estimation. A 1D Kalman filter is small, but it is still a state estimator. Treat it like one.
Why this matters for commissioning risk
Custom ST on a live controller introduces real failure modes. Poorly bounded loops, bad initialization, divide-by-near-zero conditions, or simple logic errors can trigger watchdog faults or unstable behavior depending on platform and implementation. OLLA Lab is useful here as a bounded validation environment: engineers can compile, simulate, inject noise, and tune parameters before field deployment, where mistakes are less educational and more expensive.
What are the core mathematical equations of a 1D Kalman Filter?
A 1D Kalman Filter estimates a single scalar state from noisy measurements by repeating a predict phase and an update phase every scan. In PLC terms, it is a recursive estimator that decides how much to trust the model versus the incoming sensor value.
Core variables
The filtered value you want to use downstream.
- X — Current state estimate
The retained estimate from the prior scan.
- X_prev — Previous state estimate
A measure of uncertainty in the current estimate.
- P — Estimation error covariance
The retained covariance from the prior scan.
- P_prev — Previous estimation error covariance
The assumed uncertainty in the system itself. Higher `Q` makes the filter respond faster to change.
- Q — Process noise covariance
The assumed uncertainty in the sensor measurement. Higher `R` makes the filter trust the sensor less.
- R — Measurement noise covariance
The dynamic weighting factor between prediction and measurement.
- K — Kalman gain
The noisy process variable entering the filter.
- Raw_Input — Measured sensor value
Predict and update equations
For the simplest 1D form, where the state is assumed to persist between scans without a more detailed motion model:
Predict phase
- `P = P_prev + Q`
Update phase
- `K = P / (P + R)`
- `X = X_prev + K * (Raw_Input - X_prev)`
- `P_prev = (1 - K) * P`
- `X_prev = X`
Operational meaning of Q and R
The tuning behavior is governed mainly by `Q` and `R`.
- Increase Q when the underlying process can change quickly and the estimator must adapt faster.
- Increase R when the sensor is noisy and the estimator should trust measurements less.
- If Q is too low, the filter becomes sluggish.
- If R is too low, the filter follows noise too eagerly.
- If both are guessed badly, the result is still a filter, just not a useful one. Mathematics is not a substitute for process understanding.
How do you write a 1D Kalman Filter in IEC 61131-3 Structured Text?
A minimal implementation requires retained variables, explicit initialization, and one execution path per scan. The code below is intentionally simple and suitable for adaptation into a function block or cyclic program section.
### Example: 1D Kalman Filter in Structured Text
Structured Text example:
VAR Raw_Input : REAL; // Noisy sensor input Filtered_Output : REAL; // Filtered result
X : REAL; // Current state estimate X_prev : REAL := 0.0; // Previous state estimate
P : REAL; // Current error covariance P_prev : REAL := 1.0; // Previous error covariance
Q : REAL := 0.01; // Process noise covariance R : REAL := 0.10; // Measurement noise covariance
K : REAL; // Kalman gain
InitDone : BOOL := FALSE; END_VAR
// One-time initialization IF NOT InitDone THEN X_prev := Raw_Input; P_prev := 1.0; InitDone := TRUE; END_IF;
// Predict phase P := P_prev + Q;
// Update phase K := P / (P + R); X := X_prev + K * (Raw_Input - X_prev);
// Store for next scan P_prev := (1.0 - K) * P; X_prev := X;
// Output Filtered_Output := X;
Implementation notes that matter on a real PLC
- Initialize from the first live measurement rather than zero when possible. This avoids a needless startup transient.
- Retain only what the algorithm needs. In this simple form, that is primarily `X_prev` and `P_prev`.
- Use floating-point types appropriate to the platform. Some PLCs treat `REAL` and `LREAL` differently enough to matter in tuning stability.
- Avoid hidden reinitialization. If `InitDone` resets unexpectedly, the filter will appear to “jump” on restart.
- Keep the execution deterministic. The filter should run once per scan or once per scheduled task, not opportunistically.
When to wrap this in a function block
A function block is preferable when you need:
- multiple instances for different sensors,
- explicit encapsulation of state,
- standardized initialization behavior,
- cleaner reuse across projects.
That is usually the right production pattern. The inline version is still useful for understanding and bench validation.
How can you test filter response against injected noise in OLLA Lab?
Testing is the difference between writing code and validating behavior. OLLA Lab is relevant here because it provides a browser-based environment to rehearse the risky part: proving the filter under noisy, changing, and fault-like conditions before it touches a live process.
Define “Simulation-Ready” correctly
Simulation-Ready does not mean “able to write PLC syntax from memory.” It means an engineer can prove, observe, diagnose, and harden control logic against realistic process behavior before it reaches a live system. That includes watching I/O, comparing ladder or ST state against simulated equipment state, injecting abnormal conditions, and revising logic after a failure case.
That is a stricter standard than tutorial completion. It is also closer to actual commissioning.
A practical OLLA Lab test workflow
- Open the Variables Panel.
- Map `Raw_Input` to a simulated analog source in the Signal Simulator.
- Use a slow sine, ramp, or step-like analog profile to represent a changing process value such as tank level, pressure, or flow.
- Overlay noise on the base signal to simulate vibration, turbulence, or electrical interference.
- Start with moderate noise, then increase amplitude to test estimator robustness.
- Trend `Raw_Input` and `Filtered_Output` together.
- Watch whether the filtered signal suppresses noise without falling materially behind the underlying waveform.
- Increase `R` if the filter follows noise too closely.
- Increase `Q` if the filter is too slow to track genuine process movement.
- Introduce step changes, spikes, or sudden process reversals.
- Confirm the estimator recovers cleanly and does not destabilize downstream logic.
- Bind the raw signal
- Apply a base waveform
- Inject measurement noise
- Observe filtered response
- Tune Q and R live
- Test abnormal transitions
What OLLA Lab is and is not doing here
OLLA Lab is a validation and rehearsal environment for high-risk commissioning tasks. In this context, it lets engineers test ST logic, inspect variable behavior, and compare simulated process response against algorithm output without risking a physical controller or live plant sequence. It is not a substitute for site acceptance, loop checkout, safety validation, or operator training on the actual asset. Those boundaries matter.
What is the difference between a Kalman Filter and a low-pass filter in process control?
A low-pass filter suppresses high-frequency variation by smoothing the signal over time. A 1D Kalman Filter estimates the most likely true state by balancing prior estimate uncertainty against measurement uncertainty. The first is straightforward smoothing; the second is recursive estimation.
Practical comparison
| Criterion | First-Order Lag / Low-Pass Filter | 1D Kalman Filter | |---|---|---| | Primary method | Time-based smoothing | Predictive state estimation | | Main tuning terms | Time constant / filter coefficient | Process noise `Q`, measurement noise `R` | | Response to noise | Good | Good | | Response lag | Often significant | Often lower when tuned well | | Model awareness | Minimal | Explicit uncertainty weighting | | PLC implementation complexity | Low | Moderate | | Best use case | Simpler applications where lag is acceptable | Noisy measurements where responsiveness still matters |
The control consequence is not subtle
If a low-pass filter adds enough phase lag, the loop may look calmer on the trend while performing worse in operation. That is the trap. A trend that flatters the eye can still punish the actuator.
A bounded engineering claim
A 1D Kalman Filter is not automatically better than a low-pass filter. It is better suited when:
- sensor noise is material,
- process response matters,
- downstream PID or alarm logic is sensitive to delay,
- and the engineer can tune `Q` and `R` with some discipline.
If the application is slow, forgiving, and noncritical, a simple low-pass filter may be entirely adequate. Complexity should earn its keep.
What engineering evidence should you keep when validating a filter?
Screenshots are not engineering evidence by themselves. They are souvenirs unless tied to a test definition.
When documenting filter validation, build a compact body of evidence using this structure:
- System Description Define the simulated asset, sensor type, process variable, scan context, and downstream control relevance.
- Operational definition of “correct” State what success means in observable terms, such as reduced variance, acceptable tracking delay, stable PID behavior, or reduced false alarm chatter.
- Ladder logic and simulated equipment state Record the control logic context and the simulated process behavior at the time of test.
- The injected fault case Specify the noise profile, spike condition, dropout, or disturbance introduced.
- The revision made Document the parameter changes, code changes, or initialization changes applied.
- Lessons learned Capture what tuning assumption held, what failed, and what should be checked before deployment.
This is the kind of evidence that survives review. A screenshot gallery rarely does.
What standards and literature matter when applying filtering logic in PLC environments?
Filtering is not a functional safety claim by itself, but implementation quality still sits inside a broader discipline of software correctness, validation, and control performance. The relevant standards and literature help frame what good engineering looks like.
Standards context
- IEC 61131-3 governs PLC programming languages, including Structured Text and Ladder Diagram. It is the language framework relevant to implementation form.
- IEC 61508 is relevant when software behavior affects safety-related systems or lifecycle rigor. It does not “approve” a Kalman filter, but it does sharpen expectations around verification, traceability, and software integrity.
- Guidance from organizations such as exida is useful when discussing validation discipline, fault behavior, and separation between control convenience and safety function.
Literature context
Recent literature across process control, sensor fusion, and digital simulation generally supports a few bounded conclusions:
- industrial measurements are routinely corrupted by noise and disturbance;
- filtering choices affect both signal quality and control responsiveness;
- simulation and digital twin environments can improve pre-deployment validation when they are used to test observable behavior rather than merely demonstrate graphics;
- AI-assisted programming can accelerate drafting, but deterministic review remains essential.
That last point deserves plain language: generated code is still your problem once it reaches a controller.
Conclusion
A 1D Kalman Filter is useful in PLC work because it addresses a real plant problem: noisy measurements that cannot be smoothed with heavy lag without degrading control quality. Structured Text is the correct implementation medium for this algorithm because the method depends on retained state and compact numerical expressions. OLLA Lab becomes operationally useful at the validation stage, where engineers need to inject noise, trend response, tune `Q` and `R`, and harden logic before deployment.
The distinction worth keeping is simple: filtering is not just about making a trend look cleaner; it is about preserving decision quality under noise. In process control, that difference reaches the actuator quickly.
Keep exploring
Interlinking
Related reading
How To Tune A Pid Loop A Practical Olla Lab Guide →Related reading
How To Build 3 Sigma Failure Detection For Pumps In Ladder Logic →Related reading
How To Scale 4 20ma Analog Signals And Program Fault Handling In Olla Lab →Related reading
Explore the full Ladder Logic Mastery hub →Related reading
Related article 1 →Related reading
Related article 2 →Related reading
Related article 3 →Related reading
Practice this workflow in OLLA Lab ↗