Implementing Inbuilt Simulators in Siemens S7 PLC Projects

David Krause18 min read
S7-300SiemensTutorial / How-to
Licensed PE Working through this on a live machine? A Maine-licensed engineer can take it from here — included with IMD hardware, by the hour for everything else. Book an engineer

Overview

An inbuilt simulator is a parallel logic block inside the PLC program that mimics the behaviour of the field devices (sensors, motors, valves, contactors) so that the application code, the HMI screens, the alarm handling, and the datalogging layers can be exercised end-to-end without a single piece of product, cable, or I/O card being present. The technique is platform-agnostic in principle, but it is particularly effective on Siemens SIMATIC S7-300/S7-400 controllers programmed with STEP 7 V5.x because the controller's scan budget, its ability to hold dual code paths in separate FBs, and the deterministic execution of IEC timers make it an ideal host for a "virtual plant".

The driver for adopting an inbuilt simulator is rarely curiosity; it is almost always a commercial constraint. Once a controller has been accepted at the Factory Acceptance Test (FAT) it is normally shipped to the customer, often hundreds of kilometres away. Driving to site for every program modification is expensive, and shipping the controller back to the workshop is even more expensive. An inbuilt simulator removes the dependency on the physical process and converts the problem from a logistics exercise into a software exercise: a laptop with STEP 7, an Ethernet cable, and a copy of the project is everything the engineer needs to keep the code moving forward.

This article covers the architectural decisions, the practical STEP 7 patterns, and the verification steps required to embed a robust simulator into a live S7 project. It also explains why S7-PLCSIM is not always the right tool and how to work around its most limiting recorder bug.

When an Inbuilt Simulator Beats S7-PLCSIM

S7-PLCSIM is the standard Siemens off-line simulator. It loads the compiled STEP 7 program into a virtual CPU that runs on the engineering station. Inputs are forced through the PLCSIM GUI or via WinCC flexible / TIA Portal test environments; outputs are observed but never reach a real field device. For unit-testing small FBs it is excellent, but for full-loop, multi-month commissioning programmes it has three structural weaknesses that an inbuilt simulator does not share:

Concern S7-PLCSIM Inbuilt Simulator
Process fidelity Requires the engineer to manually toggle every input bit from a table. Useful for logic, painful for sequences. Drum logic and state machines inside the PLC automatically advance the simulated process step-by-step.
Recorder playback Snapshots the entire I/O byte instead of the individual bit you were operating. Subsequent bit-level forces are overwritten on replay. Not applicable – the simulator generates its own signals deterministically.
Hardware I/O dependency Hardware configuration must be downloaded separately; ET200 stations and PROFIBUS slaves are not always modelled. The simulated I/O lives in DBs and M-bit shadows; the real I/O is bypassed at compile time, not at runtime.
HMI integration ProTool/ WinCC flexible can connect to PLCSIM as a substitute PLC; this works well. HMI connects to the real CPU; the simulator runs on the same CPU, so all HMI tags are real.
Customer acceptance Difficult to demonstrate live to a customer who wants to see their actual panel. Runs on the customer's CPU; the operator can use the real OP/TP as if the line were running.

The fundamental advantage of an inbuilt simulator is that the simulation and the application code share the same scan, the same memory model, and the same tag database. The HMI, the historian, the OPC server, and the remote SCADA all see one consistent plant image, even if that image is being generated by a mathematical model rather than by physical hardware.

Prerequisites

Before adding a simulator to an existing S7 project, verify the following:

  1. STEP 7 V5.5 SPx or TIA Portal V13+ is installed with the matching S7-PLCSIM option. The inbuilt simulator itself does not require PLCSIM, but you will use it for unit tests on FBs before integration.
  2. Free work memory in the CPU. A typical 50-step drum-based simulator with two or three simulated stations consumes 8–14 KB of work memory and roughly 4 KB of load memory. Check with PLC > Module Information > Memory in STEP 7 or via SFC51 (SSL_ID 0115) at runtime.
  3. Free DB numbers in the range that is not auto-assigned by the SFC/SFB generator (avoid DB1, DB2, DB3, DB5, DB7–DB15, and any DBs already used as instance DBs).
  4. A consistent I/O symbol table. Simulated signals must use a naming convention that distinguishes them from real signals at a glance. A common scheme is to prefix simulated tags with SIM_, for example SIM_Cyl1_Extended, SIM_Part_Present, SIM_Motor1_Running.
  5. Access to the field wiring diagrams so that you can build an accurate state-by-state model of every device the application code expects to read or write.
  6. Step 7 standard library blocks: FB 3 (TP – pulse), FB 4 (TON – on-delay), FB 5 (TOF – off-delay), FB 9 (S/PD – selectable pulse/extended), SFB 0/1/2 (CTU/CTD/CTUD), and SFC 64/65 (RD/T_DIS – read system time) are sufficient for the vast majority of drum-based models.

Simulator Architecture

The recommended architecture separates the simulator into three layers, each implemented in its own FB/DB pair:

  1. Hardware Shadow DB – a single DB (e.g. DB 900 "SIM_Shadow") that contains a Boolean for every digital input and every digital output used by the application. The application code reads inputs from this DB in simulation mode and writes outputs to it. In real mode the application reads from PEW / PED and writes to PAW / PAD via process image partitions. A central SIM_MODE flag in DB 901 selects which source the application uses.
  2. Process Model FB – a cyclic FB (e.g. FB 910 "SIM_Process") that contains the state machines and the timers for the modelled devices. The FB takes the application's outputs (e.g. Motor1_Start) and, after the realistic mechanical/electrical delay, asserts the corresponding shadow inputs (e.g. SIM_Motor1_Running).
  3. Scenario Driver – a higher-level FB (e.g. FB 920 "SIM_Scenario") that orchestrates multi-step product flows. It uses drum logic to advance a virtual part through the line: load, clamp, drill, unclamp, eject, return to home. The driver exchanges handshakes with the process model FB so that the simulated sequence only advances when the application code has actually requested the next action.

The key design rule is that the simulator must never know it is being simulated. From the application code's point of view, every input and every output is real. The only point of contact is the SIM_MODE selector and the shadow DB. This is what allows the HMI, the alarms, and the SCADA to keep working unchanged.

I/O Addressing Philosophy and PLC-SIM Compatibility

One of the most important architectural decisions you make when designing a PLC program is how to group the I/O points on the cards. There are two schools of thought:

Strategy Description Strength Weakness
Spread I/O Related signals are distributed across many cards, often with redundancy, so that a single card fault affects only a small fraction of the plant. Maximum availability; the rest of the plant keeps running. PLC-SIM recorder overwrites neighbouring bits on playback; simultaneous interactive testing is impossible.
Grouped I/O All signals belonging to a single sub-system are placed on the same input card and the same output card. A card fault is confined to a single, clearly bounded sub-system; diagnosis is trivial. PLC-SIM recorder remains a nuisance, but the inbuilt simulator is unaffected because the simulator does not need to force external bits – it overwrites the shadow DB directly.

For a project that is going to carry an inbuilt simulator, the grouped approach is preferred. The shadow DB is the boundary, and the simulator writes to it with the same bit-level granularity regardless of how the real I/O is laid out. PLC-SIM's byte-level recorder bug is irrelevant because the inbuilt simulator is not using PLC-SIM at all in production.

Process Modelling Techniques

A "process model" is a mathematical or state-based representation of the physical equipment. The complexity of the model should be matched to the accuracy you need from the test. There are four levels of fidelity that engineers typically adopt:

Level 1 – Bit-Set Model

The simplest possible model. As soon as the application sets a motor starter output, the corresponding contactor feedback input is set true, possibly after a single TON timer representing the contactor pickup time. Suitable for uncommissioned desk reviews of start/stop logic.

// FB 911 "SIM_Motor" - minimal model
// Inputs:  Start (BOOL), Stop (BOOL), Fault (BOOL)
// Outputs: Running (BOOL), AtSpeed (BOOL), Tripped (BOOL)

A #Start
AN #Stop
AN #Fault
S #Running // contactor is energised

A #Running
L S5T#800MS // typical 0.5–1.0 s contactor pickup
SD #Delay1
A #Delay1
S #AtSpeed // motor reaches rated speed

A #Fault
S #Tripped

Level 2 – Timer-Based Model

Each simulated actuator has a TON/TOF pair that models the extend and retract strokes. The simulator listens to the application's output bits and, when the appropriate time has elapsed, sets the corresponding sensor feedback bits in the shadow DB. This is the workhorse of most inbuilt simulators.

Level 3 – Drum-Based Model

A drum (also called a sequencer or step counter) is a state machine that advances through a list of predefined steps based on time or external events. Drums are ideal for batch processes where the same sequence of actions is repeated every cycle. The classic TI drum from the 5TI/PM550 lineage is a binary word that rotates through a mask; in modern STEP 7 the equivalent is built from a CTU counter and a CASE construct inside an FB.

// FB 921 "SIM_Drum8" - 8-step time-and-event drum
// Inputs:  StepTime (TIME), AutoStart (BOOL), ManualStep (BOOL)
// Outputs: Step1..Step8 (BOOL array), StepNo (INT)

// Time-driven advance
A #AutoStart
L #StepTime
SD #StepTimer
A #StepTimer
CU #StepCount // 0..7 rolling

// Manual advance (for break-points during fault injection)
A #ManualStep
CU #StepCount

// Decode step number to one-hot outputs
L #StepCount // ACCU1
T #StepNo

A L 0.0
= #Step1
A L 0.1
= #Step2
... etc through to Step8

// Reset on completion
L #StepCount
L 8
>=I
R #StepCount

The drum above is event- AND time-driven. In practice you wire the output of a real sensor (the cylinder extended limit switch, for example) into the manual advance input so that the drum only progresses when the application code has actually caused the cylinder to extend. The result is a closed loop in which the application drives the actuator, the simulator detects the actuation, the drum advances one step, and the simulator asserts the next virtual process condition.

Level 4 – Equation-Based Model

For continuous processes (tanks, flow loops, level control) the drum is replaced by an explicit integrator. A typical level model is:

// Discrete-time level update, scan period Ts = OB1 cycle time
// Level(n+1) = Level(n) + (Inflow - Outflow) * Ts / Area

L #Level
L #Inflow
-R
L #Outflow
+R // ACCU1 now holds (Inflow - Outflow) * 1
L #Ts // 100 ms typical
*D
L #Area
/R // units: m per scan
T #dLevel

L #Level
L #dLevel
+R
T #Level

// Limit check
L #Level
L 0.0
<R
R
L 3.5 // tank height in metres
>R
SPB OVR

// Overflow clamp
OVR: L 3.5
T #Level
NOP 0

This kind of model is identical in structure to what you would find in a high-fidelity external package such as VisSim or MATLAB/Simulink, but it runs on the same scan as the PID controller it is feeding, so the loop closure is bit-exact. Engineers who come from a process control background – DCS migration projects, refinery unit control, water treatment – will recognise the approach immediately.

Step-by-Step Implementation

  1. Inventory the I/O. Export the symbol table from STEP 7 and split it into three groups: Real Digital Inputs, Real Digital Outputs, and Derived (computed) inputs such as contactor feedbacks that you intend to model. The first two groups are the boundary; the third group is what the simulator will generate.
  2. Create the shadow DB (DB 900 "SIM_Shadow") with one BOOL per derived input and one BOOL per output the application writes to. Use the same symbol names as the real I/O with a SIM_ prefix to keep the HMI symbol table readable.
  3. Insert the mode selector. In OB 1, branch on DB901.DBX0.0 "SIM_MODE":
    // Real I/O read
    A "SIM_MODE"
    JC SIM1
    L PED 0 // process image of input card 0
    T DB900.DBD 0 // copy to shadow
    JU END1
    SIM1: // Simulator already maintains DB900 directly
    NOP 0
    END1: NOP 0

    The application's input reads are then changed from A I 0.0 to A DB900.DBX0.0. In simulation mode the simulator writes the bits; in real mode the I/O read at the top of OB1 copies them in. The same pattern is used for outputs in reverse.

  4. Build the per-actuator model FBs (FB 911, 912, 913, …) for each motor, valve, and cylinder that has a feedback signal. Each FB owns the TON/TOF timers it needs; pass them as IN_OUT parameters to keep the FB re-usable.
  5. Build the scenario driver FB (FB 920) that contains the drum(s) for each simulated station. The drum output bits are written into DB 900 as the derived inputs become true.
  6. Call the simulator FBs from OB 35 (a 100 ms cyclic interrupt OB) so that the simulation runs on a fixed time base, decoupled from OB 1's variable cycle time. OB 35 is preconfigured in the S7-300 CPU hardware at a default 100 ms; adjust in the CPU properties if your model needs a 50 ms or 200 ms period.
  7. Add a "Force Fault" panel on the HMI that toggles simulator-only fault bits in DB 901. These bits are OR-ed with the real fault inputs; in simulation mode the engineer can inject a motor overload, a sensor failure, or a network timeout to verify the application's fault handling without touching the real plant.
  8. Document the simulation matrix in the project Functional Specification. For every I/O point list whether it is real, derived, or computed; for every derived point list the source FB and the timer value used. This table is your audit trail for the customer's acceptance engineer.

HMI Integration

Because the simulator runs on the real CPU, the HMI connection is unchanged. ProTool, WinCC flexible, or TIA Portal WinCC all connect to the PLC over MPI/Profibus/Industrial Ethernet exactly as they do in production. There is no need for the HMI to know that a simulator is running; the only visible difference is the value of a status bar tag such as SIM_MODE displayed in the header of every screen.

If you also use S7-PLCSIM for early-stage desk work, the standard pattern is to run the PLCSIM instance on the engineering laptop, configure the HMI's PLC connection to point at the virtual CPU, and use ProTool's "RT" (Runtime) mode for the screens. PLCSIM acts as a faithful substitute CPU, and the HMI is none the wiser. This is the configuration the development team will use at the desk; the inbuilt simulator is what the commissioning team will use on the customer's site where a real CPU is already installed but the line is not yet ready.

PLC-SIM Recorder Workaround

S7-PLCSIM's recorder is meant to capture a sequence of bit-level operations and replay them for regression testing. In practice it does not work at bit level: when you record an event on bit I 0.3, PLCSIM stores a snapshot of the entire input byte IB 0. When you later manually set I 0.5 in the same byte, the next replay of the original event will overwrite I 0.5 with the value it had at record time. The result is that any bit you want to interact with during playback must be in a different byte from any bit you have recorded.

There are three practical workarounds, in order of increasing effort:

  1. Avoid the recorder for any non-trivial test. Use PLCSIM as a virtual CPU and drive it from a script in your test framework, or from a hand-typed sequence in the PLCSIM input table.
  2. Restructure the I/O to spread simulation-critical bits across many bytes, the inverse of the grouped I/O approach above. This is only sensible if the I/O layout is still in the design phase.
  3. Use the inbuilt simulator instead of PLCSIM for any full-loop test. The recorder is a non-issue because the simulator does not need to record anything; it generates signals directly.

Verification and Commissioning

After the simulator is installed, the following checks must be performed before the project is handed over to the customer:

  1. Mode switch test. Toggle SIM_MODE from the HMI. Verify that all derived inputs freeze, all real inputs start to be processed, and that the application transitions cleanly without any latched alarms.
  2. Round-trip test. With the simulator in Auto mode, run a complete product batch from the HMI start command through to the end-of-batch report. Capture the resulting datalog file and compare it against the FAT baseline. Any divergence indicates a model that does not accurately reflect the real process.
  3. Fault injection test. Use the Force Fault panel to trigger every documented fault. Verify that the application responds as specified: alarm raised, machine stopped, sequence aborted, re-start blocked until reset.
  4. Performance test. With the simulator active, monitor OB 1 cycle time via SFC 78 (READ_SZL) or the online diagnostics. The simulator should add less than 5 % to the worst-case cycle time. If it adds more, the per-actuator FBs need to be lighter or the scenario drum should be split across multiple OBs.
  5. Memory test. Verify that load memory and work memory consumption remain below 80 % of the available budget.
  6. Regression baseline. Save the project with a version label (e.g. V1.0_SIM_ACTIVE) and archive it. The customer's acceptance engineer should be given a checklist that confirms the simulator can be disabled by turning off the SIM_MODE bit, and that with the simulator off the application behaves exactly as it did at FAT.

Performance and Resource Sizing

For a typical mid-size S7-300 station with 256 digital I/O and 12 motor starters:

Resource Without simulator With inbuilt simulator Delta
Work memory (code) 110 KB 122 KB +10.9 %
Work memory (data) 34 KB 41 KB +20.6 %
Load memory 410 KB 445 KB +8.5 %
OB 1 cycle (worst) 22 ms 24 ms +9.1 %
OB 35 cycle 100 ms (timer tick only) 100 ms (model + timers) ~0 %
FBs added 0 14 +14
DBs added 0 3 (shadow, mode, scenario) +3

On an S7-315-2 PN/DP with 384 KB work memory, this is comfortably within budget. On a smaller S7-312 with 32 KB work memory, the simulator would consume a third of the available code space and the project should be migrated to a larger CPU or split across two stations.

Common Pitfalls

  • Forgetting the mode switch. The most common bug found during site commissioning is that the simulator is left enabled and the real process is run on top of the simulated signals. Make the SIM_MODE tag prominently visible on the HMI and require a confirmation click to enable it.
  • Hidden feedback loops. If a motor's contactor feedback is wired to the simulator and the simulator's "motor is running" output is wired back into the same FB, an infinite oscillation can occur. Always close the loop through the application's output, not through the simulator's internal outputs.
  • Wrong timer base. The TON block in STEP 7 accepts an S5TIME value, not an IEC TIME. A value of S5T#10S means 10 seconds; a value of S5T#100MS means 100 milliseconds. An S5T#5S5 means 5.5 seconds. Do not confuse this with T#10s, which is an IEC TIME and is only valid in S7-1500/1200 code.
  • Instance DBs being regenerated. If you store the simulator's instance DBs in the program and the user re-instances the FBs, the internal counters will be reset. Lock the FBs in the program or use a single-instance DB that is never regenerated.
  • Time-zone bugs in SFC 64. RD_SYS_T returns the local time as DATE_AND_TIME; in plants spanning time zones the time arithmetic can drift. Use the UTC variant SFC 79 (SET_TIMEZONE) or store your own epoch counter if absolute time stamps matter for the simulation log.

FAQ

What is the difference between an inbuilt PLC simulator and S7-PLCSIM?

S7-PLCSIM is an off-line virtual CPU that runs on the engineering station; you force inputs by hand or by recording them. An inbuilt simulator is a parallel code path that runs on the real CPU and uses drum logic and timers to model the field devices, so the HMI and the SCADA see a fully behaving plant without any external forcing tool. For full-loop tests of any non-trivial sequence, the inbuilt simulator is almost always more productive.

How much extra memory does an inbuilt simulator need on an S7-300?

A typical 12-motor, 256-I/O simulator with a three-station scenario drum consumes roughly 12 KB of work memory and 4–6 KB of load memory, i.e. about 10 % of the code budget on a CPU 315-2 PN/DP. The exact figure is available from PLC > Module Information > Memory after the first download.

Why does the S7-PLCSIM recorder overwrite neighbouring bits?

The recorder takes a byte-level snapshot of the input or output byte containing the bit you are operating, not a bit-level snapshot. On playback the byte is written back as a whole, so any bit you have forced manually in that same byte is overwritten. The fix is to either avoid the recorder and drive PLCSIM from a script, or to use an inbuilt simulator that does not rely on PLCSIM's I/O forcing at all.

Can I run the inbuilt simulator on a customer CPU that is already installed on site?

Yes. That is its main use case. Toggle the SIM_MODE bit from the HMI or via a password-protected screen, and the application will run against the simulated process while the real field wiring remains disconnected. This is the standard pattern for off-line testing during the weeks between FAT and Site Acceptance Test (SAT).

Which OB should host the simulator FBs?

OB 35 (100 ms cyclic interrupt) is the recommended host. It gives the simulation a fixed time base independent of the OB 1 scan time, and it is present by default on every S7-300 and S7-400 CPU. For models that need higher resolution (e.g. fast pneumatic actuators) configure OB 32 for 10 ms; for slow thermal models OB 35 at 100 ms is sufficient.

Back to blog