Chapter 14
Real-Time Simulation, HIL and Digital Twins
Bachelor Program in Mechatronics Engineering
Mechatronic System Modeling & Simulation
•
Bachelor
Real-Time Simulation, HIL and Digital Twins
Introduction
Modern mechatronic products are increasingly cyber-physical systems: mechanical structures, actuators, sensors, embedded software, communication networks and supervisory analytics operate as one engineered system. Testing such systems only after physical prototypes are available is expensive and may be unsafe. Real-time simulation, rapid control prototyping, software-in-the-loop (SIL), hardware-in-the-loop (HIL) and digital twins provide progressively more realistic ways to design, verify, operate and maintain mechatronic equipment.
A simulation model is useful only when its fidelity, execution speed and uncertainty are appropriate for the engineering decision. A detailed finite-element model may predict stress accurately but be too slow for controller testing. Conversely, a reduced-order model may execute thousands of times faster but omit flexible modes that are important to vibration control. Engineering judgement therefore concerns not only whether a model is mathematically correct, but also whether it is fit for purpose.
Learning objectives
By the end of this chapter, the reader should be able to:
distinguish offline, real-time, SIL, rapid-control-prototyping and HIL simulation;
reduce a physical model while preserving behaviour relevant to control;
assess sampling, solver, latency and numerical-stability requirements;
design a basic HIL experiment and explain its benefits and limitations;
describe digital-twin architecture, IoT connectivity and model updating;
apply condition-monitoring and predictive-maintenance concepts; and
evaluate validation, cybersecurity, safety and governance issues.
1. Real-time simulation as an engineering requirement
In offline simulation, the model may take more or less wall-clock time than the phenomenon being represented. In real-time simulation, the computation must keep pace with physical time. If a simulator uses a fixed step Δt, each calculation must finish before the next deadline. The real-time factor is
R = Tsim / Twall
where T_sim is the simulated time interval and T_wall is the elapsed computation time. Real-time execution requires R ≥ 1, although practical systems require margin because operating-system interrupts, communication and data logging introduce variability.
For a digital controller with sampling period T_s, the controller receives measurements and produces a control command once per sample. A simplified timing constraint is
Tcompute + Tio + Tjitter ≤ Ts
where T_compute is execution time, T_io is input/output and communication time, and T_jitter is the worst-case timing variation. This is a deadline condition, not merely an average-performance condition. A model that is usually fast but occasionally misses a deadline can produce misleading or unsafe results.
Real-time simulation commonly uses fixed-step numerical integration. For a continuous-time state model
ẋ = f(x,u,t), y = g(x,u,t)
x is the state vector, u the input vector, y the output vector and t time. Forward Euler integration gives
xk+1 = xk + Ts f(xk,uk,tk)
This method is computationally inexpensive but has limited accuracy and stability. It is appropriate only when the step is sufficiently small relative to the system dynamics. More accurate methods, such as fourth-order Runge–Kutta, require additional function evaluations and may be unsuitable when the processor has a strict deadline.
For the scalar stable system ẋ = −a x, with a > 0, Euler integration produces x_{k+1} = (1 − aT_s)x_k. Numerical stability requires |1 − aT_s| < 1, hence 0 < aT_s < 2. This condition illustrates that a physically stable system can become numerically unstable when the time step is too large.
Important real-time performance measures
Measure
Meaning
Engineering concern
Step time
Time available for one model update
Must exceed worst-case execution time
Jitter
Variation in timing
Can affect sampled-data control
Latency
Delay from input measurement to output action
Changes closed-loop dynamics
Throughput
Data processed per unit time
Important for high-channel systems
Determinism
Predictability of execution timing
Essential for repeatable tests
Numerical stability
Boundedness of computed response
Depends on solver, model and step
2. From detailed models to reduced-order models
A high-fidelity model may contain thousands or millions of states. Real-time control testing generally needs a much smaller model that preserves the input–output behaviour relevant to the controller and operating range.
A common linear model is
ẋ = Ax + Bu, y = Cx + Du
where A, B, C and D are system matrices. A state is controllable if it can be driven by an admissible input; it is observable if it can be inferred from measured outputs. States that are weakly controllable or weakly observable often contribute little to the control task and may be candidates for reduction.
Physical reduction
Physical insight can remove components or dynamics that are irrelevant to the intended experiment. Examples include neglecting very stiff structural modes at low frequencies, replacing a distributed beam by a lumped mass–spring–damper model, or representing an inverter by an averaged voltage-source model when switching ripple is not under study.
For a mass–spring–damper system,
mẍ + cẋ + kx = F
m is mass in kilograms, c damping in newton-seconds per metre, k stiffness in newtons per metre, x displacement in metres and F applied force in newtons. If the excitation frequency is far below the first neglected structural resonance, a rigid-body or low-order approximation may be adequate. It is not adequate for resonance, fatigue or high-bandwidth vibration analysis.
Modal and mathematical reduction
In modal reduction, the displacement is approximated by a limited set of mode shapes:
q(t) ≈ Φr η(t)
where q is the full coordinate vector, Φ_r contains r retained mode shapes and η contains modal coordinates. The selected modes should cover the frequency range and locations of actuation and sensing. Truncation can produce errors at unmodelled resonances and may violate physical properties if performed carelessly.
Balanced truncation ranks states according to joint controllability and observability. For stable linear systems, the Hankel singular values quantify the importance of states in an input–output sense. A reduced model can be selected by retaining states with large values. The method is theoretically attractive, but computational cost and preservation of nonlinearities, constraints and physical parameters must be considered.
Nonlinear and lookup-table reduction
Many mechatronic systems are nonlinear:
ẋ = f(x,u), y = h(x,u)
One practical strategy is to linearize around an operating point and use several local models. Another is to use lookup tables, polynomial approximations or neural-network surrogates. The model must be tested between interpolation points and outside the identification data range. A fast approximation is not automatically valid under faults, saturation, friction reversal or extreme temperature.
Reduction workflow
Define the purpose: controller tuning, fault injection, thermal prediction or another task.
Identify relevant frequencies, time constants, loads and operating conditions.
Determine required input and output channels.
Remove or approximate irrelevant dynamics.
Validate the reduced model against the reference model.
Measure worst-case execution time on the target real-time platform.
Document assumptions, parameter sources and validity limits.
A useful validation error for a signal y over N samples is the root-mean-square error:
RMSE = √[(1/N) ∑k=1N (yk − ŷk)2]
where y_k is the reference value and ŷ_k is the reduced-model value. RMSE has the same units as y and should be supplemented by maximum error, phase error and task-specific measures. A low average error can conceal a dangerous peak error.
3. SIL, rapid control prototyping and HIL
Testing methods can be arranged according to how much hardware is real.
Method
Plant model
Controller
Main purpose
Model-in-the-loop
Simulated
Simulated
Early concept and algorithm verification
Software-in-the-loop
Simulated
Production or compiled software
Verify implementation and numerical behaviour
Rapid control prototyping
Simulated or physical plant
Experimental controller hardware
Tune and evaluate control rapidly
Processor-in-the-loop
Simulated plant
Target processor
Check computational implementation
Hardware-in-the-loop
Real-time plant model
Real controller hardware
Test interfaces, faults and closed-loop behaviour
Physical test
Real plant
Real controller
Final system validation
SIL can expose differences between a mathematical algorithm and production code, such as quantization, integer overflow, saturation and task scheduling. It cannot reveal all electrical interface faults or mechanical effects because the plant remains virtual.
In HIL, a real controller exchanges signals with a real-time model of the plant. The interface may include analogue and digital I/O, pulse-width-modulation capture, encoder emulation, serial buses or automotive networks. Signal scaling, polarity, timing, grounding and isolation require careful engineering.
A HIL experiment normally includes:
a plant model executing deterministically;
an I/O interface and signal conditioning;
the device under test;
a test sequencer and fault-injection mechanism; and
measurement, logging and pass/fail criteria.
The plant model must represent the dynamics visible to the controller. For example, a motor-drive HIL test may need electrical inductance, back electromotive force, mechanical inertia, load torque, sensor quantization and inverter dead time. If the purpose is only high-level state-machine testing, an averaged motor model may be sufficient.
Latency and interface fidelity
A delay τ modifies the effective loop behaviour. In frequency-domain analysis, a pure delay has transfer function
Gdelay(s) = e^(−sτ)
where s is the complex frequency variable and τ is delay in seconds. At angular frequency ω, the delay contributes phase lag −ωτ radians. Thus even a small delay can reduce phase margin in a fast control loop. HIL validation should therefore measure total sensor, computation, communication and actuator-emulation latency rather than assuming it is negligible.
Fault injection
HIL makes systematic fault testing practical. Examples include open or shorted sensors, biased measurements, stuck actuators, communication loss, excessive friction, overload, low supply voltage and intermittent encoder pulses. Faults should be introduced within safe limits, with controlled energy and clear reset procedures. A fault campaign should specify detection time, isolation behaviour, safe-state response and recovery requirements.
4. Digital twins
A digital twin is a digital representation of a specific physical asset or process that is connected to the asset through data and can support analysis, prediction or decision-making throughout part or all of its life cycle. It is more than a static CAD model and more than an unconnected simulation. The connection may be continuous or intermittent, and the twin may contain physics models, data-driven models, state estimates, historical data and maintenance records.
A practical architecture contains five layers:
Physical layer: machine, sensors, actuators and environment.
Connectivity layer: industrial Ethernet, fieldbus, wireless links, gateways and protocols.
Data layer: time-series storage, metadata, asset identity, event records and access control.
Model layer: simulation, parameter estimation, anomaly detection and remaining-useful-life models.
Application layer: dashboards, control support, maintenance planning and engineering analysis.
Digital twin architecture linking a physical asset, connectivity, models and applications
Figure: Digital twin architecture linking a physical asset, connectivity, models and applications
Figure: Bidirectional information flow in a digital-twin architecture.
The twin may operate at several synchronisation levels. At the simplest level it displays current measurements. A more capable twin estimates unmeasured states, detects deviations and updates model parameters. A predictive twin forecasts future behaviour under proposed loads or maintenance actions. Closed-loop autonomous control requires stronger validation, safety constraints and cybersecurity than monitoring alone.
State estimation and model updating
Measurements rarely reveal every state. For a linear stochastic model,
xk+1 = Axk + Buk + wk
yk = Cxk + vk
w_k and v_k represent process and measurement noise. A Kalman filter combines predictions with measurements under assumptions of linear dynamics and approximately Gaussian, white noise. Nonlinear systems may require an extended or unscented Kalman filter, particle filter or moving-horizon estimator. The method must be chosen consistently with model nonlinearities, computational resources and sensor quality.
Parameter updating can be formulated as minimising a loss function such as
J(θ) = ∑k=1N ‖yk − ŷk(θ)‖²
where θ is the parameter vector and ŷ_k(θ) is the model prediction. Identifiability is essential: if two parameters produce indistinguishable outputs under the available excitation, the data cannot reliably determine them. Updating should not blindly force a model to fit sensor faults or unrepresentative operating conditions.
5. IoT connectivity and data engineering
Industrial IoT systems connect sensors, controllers, edge computers and enterprise platforms. Connectivity decisions concern latency, bandwidth, determinism, interoperability, power, maintainability and security. A closed-loop motion controller normally remains local because cloud latency and network variability are unacceptable. Cloud services are valuable for fleet-level analytics, long-term storage and model training.
Common architectural principles include:
process safety-critical control at the edge;
timestamp measurements at their source and synchronise clocks;
preserve units, calibration status and sensor identity in metadata;
validate ranges, missing values and outliers before modelling;
separate raw data from cleaned and derived data;
use standard semantic models and documented interfaces; and
design for intermittent connectivity and graceful degradation.
Data quality is a modelling issue. A vibration signal sampled below the required bandwidth can alias high-frequency content into lower frequencies. Sensor drift, inconsistent timestamps and maintenance-induced configuration changes can create false anomalies. Data provenance must therefore accompany every prediction.
6. Condition monitoring and predictive maintenance
Condition monitoring measures indicators of asset health, such as vibration, temperature, current, acoustic emission, pressure, lubricant debris or motor torque. Maintenance decisions can be:
corrective: act after failure;
preventive: service according to time or usage;
condition-based: service when measured condition reaches a threshold; or
predictive: forecast failure risk or remaining useful life using condition and context data.
An anomaly detector identifies departure from normal behaviour. A simple standardised residual is
zk = (rk − μr) / σr
where r_k is a residual, μ_r its normal-operation mean and σ_r its standard deviation. This expression is meaningful only when the normal reference population is appropriate and approximately stable. A threshold such as |z_k| > 3 is a screening rule, not a universal law; autocorrelation, non-Gaussian noise and multiple testing affect false-alarm rates.
A residual may be defined as
rk = yk − ŷk
where y_k is measured output and ŷ_k is predicted output. Residual diagnosis must distinguish sensor faults, changes in operating regime and actual asset degradation.
Remaining useful life (RUL) is the estimated time until a specified failure criterion under stated future conditions. RUL predictions should include uncertainty, not just a point estimate. Maintenance optimisation also considers production loss, spare-part availability, labour, safety and the consequences of a missed detection.
7. Illustrative case: HIL and digital twin for a conveyor drive
Background. An illustrative manufacturing plant uses a variable-speed conveyor driven by an induction motor and gearbox. Unplanned gearbox failures stop a production line, while excessive preventive maintenance is costly.
Problem. The control team must validate a new speed controller and detect bearing degradation without risking the production machine. The existing simulation is too slow because it includes detailed electromagnetic switching and flexible-shaft dynamics.
Analysis. The controller bandwidth is below the switching frequency, so an averaged inverter model is sufficient for initial HIL testing. The drivetrain is represented by motor inertia, gearbox ratio, torsional stiffness, damping and load torque. A higher-frequency bearing model is retained only in a separate diagnostic model because it is not required for controller timing.
Approach. Engineers first perform SIL tests using production controller code. They then deploy the reduced plant model on a real-time target and connect the actual controller through encoder and torque-command interfaces. Tests include speed steps, load changes, sensor bias, encoder dropout and over-temperature. Measured HIL latency is included in controller tuning. After commissioning, an edge gateway sends synchronised motor current, speed, temperature and vibration features to a digital-twin platform. A normal-operation model generates residuals, while maintenance records label confirmed bearing replacements.
Outcome. The HIL campaign discovers a sign error in the encoder interface and a rare timing overrun that offline simulation did not show. The deployed twin does not automatically stop the conveyor; it provides graded alarms and maintenance recommendations. Engineers retain human approval for interventions and periodically review false alarms across different products and ambient temperatures.
Learning points. Model fidelity must follow the test objective. Interface errors can be as important as plant dynamics. A predictive-maintenance model requires operational context and labelled events. Safety-critical actions need independent protection, not reliance on an unverified analytics model.
8. Validation, safety and governance
Validation asks whether the model is adequate for its intended use; verification asks whether it has been implemented correctly. Both are necessary. A credible process includes requirements traceability, unit tests, conservation checks, comparison with analytical solutions, correlation against experiments, parameter uncertainty analysis and documented acceptance criteria.
Digital twins and connected HIL systems expand the attack surface. Essential controls include authenticated devices, least-privilege access, encryption where appropriate, secure boot and signed updates, network segmentation, vulnerability management, logging and tested recovery. Safety functions should be independent where a software or communication failure could create hazardous motion.
Ethical and professional responsibilities include transparent uncertainty, avoidance of unjustified automation, protection of worker and operational data, retention limits, and clear accountability for decisions. A model prediction should not be presented as a fact when it is extrapolating outside validated conditions. Cybersecurity and functional safety should be addressed during design rather than added after deployment.
9. Contemporary developments and best practice
Machine learning is increasingly combined with physical models in hybrid or physics-informed approaches. Such models can improve generalisation when data are scarce, but they still require validation, uncertainty assessment and monitoring for distribution shift. Edge AI reduces cloud dependence and latency, while federated learning can help analyse fleets without centralising all raw data. These technologies do not remove the need for sound sensors, representative experiments and engineering review.
Best practice is to:
define the decision and risk before selecting a model;
use the simplest model that meets accuracy and timing requirements;
measure worst-case execution time, latency and jitter;
validate across operating conditions, faults and sensor uncertainty;
maintain configuration, calibration and data provenance;
separate advisory analytics from safety-critical control unless formally qualified;
monitor model performance after deployment; and
retire or retrain models when assets, processes or environments change.
Chapter Summary
Real-time simulation requires deterministic execution within a physical-time deadline. Reduced-order modelling trades fidelity for speed and must preserve dynamics relevant to the intended control or diagnostic task. SIL tests software against a virtual plant, while HIL connects real controller hardware to a real-time plant model and enables repeatable interface and fault testing. Digital twins combine asset identity, connectivity, data, models and applications; their value depends on synchronisation, data quality, validation and responsible use. Condition monitoring uses measurements and residuals to identify abnormal behaviour, whereas predictive maintenance estimates future risk or remaining useful life with uncertainty. Across all these technologies, timing, model validity, cybersecurity, safety and human accountability are central engineering requirements.
Key Terms
Real-time simulation: Simulation that advances in synchronism with physical time and meets computational deadlines.
Real-time factor: Ratio of simulated time to wall-clock computation time.
Reduced-order model: Lower-complexity model retaining behaviour important to a specified task.
Model-in-the-loop: Testing in which both plant and controller are simulated.
Software-in-the-loop: Testing production or compiled controller software with a simulated plant.
Rapid control prototyping: Use of experimental controller hardware or platforms for rapid controller development.
Hardware-in-the-loop: Testing real hardware against a real-time simulation of the remaining system.
Latency: Delay between an input event and the corresponding output response.
Jitter: Variation in the timing of otherwise periodic execution.
Digital twin: Connected digital representation of a particular physical asset or process.
State estimation: Inference of unmeasured system states from a model and observations.
Residual: Difference between measured and model-predicted behaviour.
Condition monitoring: Measurement and interpretation of asset-health indicators.
Predictive maintenance: Maintenance planning based on predicted degradation or failure risk.
Remaining useful life: Estimated operating time before a defined failure or performance limit.
Identifiability: Ability of available data to determine model parameters uniquely or adequately.
Fault injection: Deliberate introduction of a simulated fault to assess system response.
Model validation: Demonstration that a model is adequate for its intended application.
Jitter: Timing variability around a nominal execution schedule.
Edge computing: Processing data near the physical source rather than exclusively in a remote cloud.
Review Questions
Short Answer Questions
What timing conditions must a real-time simulator satisfy?
Why can a physically stable system become numerically unstable in a simulation?
Distinguish SIL from HIL testing.
What is the purpose of a reduced-order model?
Why should predictive-maintenance predictions include uncertainty?
Long Answer Questions
Explain a complete workflow for developing and validating a reduced-order model for controller testing.
Describe the architecture of a digital twin and explain the function of each layer.
Compare model-in-the-loop, SIL, rapid control prototyping and HIL in terms of fidelity, cost and fault-testing capability.
Discuss how latency, jitter and numerical integration influence closed-loop HIL results.
Explain the technical, safety and ethical governance requirements for an industrial predictive-maintenance system.
Analytical / Application Questions
A real-time model has a 1 ms step time, but its measured worst-case computation is 0.92 ms, I/O takes 0.12 ms and timing margin is 0.05 ms. Determine whether the implementation meets its deadline and justify your conclusion.
Design a HIL fault-injection campaign for a servo axis. Specify at least four faults, the expected controller response and suitable pass/fail measures.
A gearbox twin produces increasing residuals during a product changeover. Analyse at least three possible explanations and propose tests to distinguish degradation from data or operating-regime changes.
Multiple Choice Questions with Answers
Question 1
Which condition is required for a fixed-step real-time simulation to meet its basic deadline?
A. Average computation time must exceed the step time
B. Worst-case computation and I/O time must fit within the step time with margin
C. The model must contain no nonlinearities
D. The simulation must use a cloud processor
Correct Answer: B. Worst-case computation and I/O time must fit within the step time with margin
Question 2
For the system ẋ = −a x integrated by forward Euler, with a > 0, which condition gives numerical stability?
A. aT_s > 2
B. aT_s = 0 only
C. 0 < aT_s < 2
D. aT_s < −2
Correct Answer: C. 0 < aT_s < 2
Question 3
What is the principal purpose of a reduced-order model in rapid control prototyping?
A. To increase the number of physical sensors
B. To preserve task-relevant behaviour while reducing computation
C. To eliminate the need for validation
D. To guarantee zero modelling error
Correct Answer: B. To preserve task-relevant behaviour while reducing computation
Question 4
In HIL testing, which element is normally real?
A. Only the plant equations
B. Only the numerical solver
C. The controller or device under test
D. None of the system components
Correct Answer: C. The controller or device under test
Question 5
A pure delay τ has which transfer function?
A. e^(sτ)
B. 1 + sτ
C. e^(−sτ)
D. τ/s
Correct Answer: C. e^(−sτ)
Question 6
Which digital-twin layer primarily provides asset data, time-series storage and metadata?
A. Physical layer
B. Data layer
C. Actuator layer
D. Mechanical layer
Correct Answer: B. Data layer
Question 7
If a measured output is 12 units and its model prediction is 9 units, what is the residual defined as measured minus predicted?
A. −21 units
B. −3 units
C. 3 units
D. 108 units
Correct Answer: C. 3 units
Question 8
Which statement best describes condition-based maintenance?
A. Maintenance occurs only after catastrophic failure
B. Maintenance is scheduled entirely by calendar time
C. Maintenance decisions use measured equipment condition
D. Maintenance is never planned
Correct Answer: C. Maintenance decisions use measured equipment condition
Question 9
Why is an averaged inverter model often used in a lower-bandwidth controller HIL test?
A. It represents every switching transient exactly
B. It reduces computation while retaining dynamics relevant to the test
C. It prevents all electrical faults
D. It requires no parameter values
Correct Answer: B. It reduces computation while retaining dynamics relevant to the test
Question 10
What does model validation primarily establish?
A. That the model is adequate for its intended use
B. That the model has infinitely many states
C. That all sensor data are correct
D. That cybersecurity is unnecessary
Correct Answer: A. That the model is adequate for its intended use
Mechatronic System Modeling & Simulation
Chapter 14
of 15