1. Problem Overview: Logging Position Data from a CPU 312C
The hydraulic-cylinder position-regulating application described in the source uses a Siemens SIMATIC S7-300 CPU 312C as the controller. The CPU runs an SFB 41 "CONT_C" continuous PID loop against a position transducer (typically a 4-20 mA / 0-10 V analog input or SSI absolute encoder), and the operator needs a sampled log of the loop variables for later review in Excel. Sample period is 100 ms or faster; total captured length is on the order of 10 seconds (the source explicitly states 100 samples in 10 s, i.e. one sample per 100 ms).
The CPU 312C is the most resource-constrained member of the S7-300 compact family. Before any data-logging architecture is committed to, the engineer must understand the limits:
| Parameter | CPU 312C (6ES7312-5BE03-0AB0) | CPU 312C (6ES7312-5BF04-0AB0) | CPU 313C-2 DP reference |
|---|---|---|---|
| Work memory (code + data) | 16 KB | 16 KB | 32 KB |
| Load memory (MMC) | 4 MB max via MMC | 8 MB max via MMC | 8 MB max via MMC |
| Bit execution | 0.2 µs | 0.1 µs | 0.1 µs |
| DI / DO onboard | 10 DI / 6 DO | 10 DI / 6 DO | 16 DI / 16 DO |
| AI / AO onboard | 0 | 0 | 4 AI / 2 AO |
| Counters | 2 (10 kHz) | 2 (10 kHz) | 3 (30 kHz) |
| Maximum DBs | 511 | 511 | 511 |
| Maximum DB size | 8 KB | 8 KB | 16 KB |
| SFB 41 instance support | Yes (work memory permitting) | Yes (work memory permitting) | Yes |
| Integrated MPI / DP | MPI | MPI | MPI + DP master/slave |
Reference: SIMATIC S7-300 CPU 312C / 313C Manual (Siemens Online Support).
2. Architecture: From Cylinder Sensor to Excel Cell
The reference implementation follows a five-stage pipeline:
- Analog acquisition - Position transducer on AI channel of an SM 331 (e.g. 6ES7331-7KF02-0AB0) or onboard DI fast counters if an SSI / incremental encoder is used.
- PID loop - SFB 41 "CONT_C" runs in OB35 (100 ms), outputs LMN (manipulated variable) to the proportional valve via SM 332 AO.
- Acquisition buffer - A dedicated FIFO DB captures PV (process value), SP (setpoint), LMN, and a millisecond timestamp on every OB35 pass.
- OPC mirror - When the FIFO reaches its trigger length, SFC 20 "BLKMOV" copies the buffer to a second DB exposed to the SIMATIC NET OPC server.
- Excel sink - The OPC server is read by either an Excel VBA macro (OPC DA Automation wrapper) or by a third-party OPC client (MatrikonOPC, Kepware, Softing) that exports CSV.
3. Configuring OB35 for 100 ms Cyclic Sampling
The S7-300 family includes eight cyclic interrupt OBs with priorities 2-24 (OB 30 through OB 38). OB35 is the default 100 ms OB and is the natural choice for hydraulic position loops, which typically have a closed-loop bandwidth of 1-3 Hz.
OB35 properties to configure in HW Config > CPU 312C Properties > Cyclic Interrupts:
| Parameter | Recommended value | Comment |
|---|---|---|
| OB35 scan time | 100 000 µs (100 ms) | Match hydraulic response time, not PID algorithm sample time |
| Phase offset | 0 ms (or staggered) | Use offset to avoid simultaneous OB1 + OB35 scan spikes on slow CPUs |
| Priority | 12 (default) | Higher than OB1 (priority 1) and time-of-day OB (priority 2) |
| Run-time monitor | Default 5000 ms | If OB35 exceeds this, CPU enters STOP with SF diagnostic |
Reference: S7-300 Programmable Controller - CPU 31xC Technological Functions Manual.
3.1 Programmatic retrieval of OB35 execution count
To timestamp each sample without an external RTC, read the CPU system clock via SFC 1 "READ_CLK" and store the date/time in BCD format inside the FIFO entry. A tighter alternative is to use the OB35-PY (start time of OB35 invocation in milliseconds since last cold restart).
// STL - OB35 preamble
CALL SFC 1 "READ_CLK"
RET_VAL := MW 100
CDT := DB100.SYSTIME[0] // DATE_AND_TIME, 8 bytes
4. Designing the FIFO Data Block
Two DBs are required:
- DB100 "FIFO_BUF" - 8 KB maximum, internally organized as an ARRAY[1..N] of a UDT or STRUCT. This is the acquisition ring written by OB35.
- DB200 "OPC_MIRROR" - Same layout as DB100, exposed to the OPC server. The acquisition code never touches this directly; SFC 20 BLKMOV copies from DB100 to DB200 at the end of each capture window.
4.1 Sample UDT
// UDT 10 "SAMPLE"
TYPE UDT 10
STRUCT
t_ms : DWORD; // OB35 PY time-stamp in ms
t_ibt : DATE_AND_TIME;// SFC 1 wall-clock (8 bytes BCD)
pv_mm : REAL; // Process value (position, mm)
sp_mm : REAL; // Setpoint
lmn_pct : REAL; // Manipulated value -100..100 %
err_v : REAL; // SP - PV
pad : WORD; // 16-bit padding to DWORD boundary
END_STRUCT;
END_TYPE
One sample = 8 + 8 + 4 + 4 + 4 + 4 + 2 = 34 bytes (padded to 36 if the compiler inserts 2 alignment bytes). Plan capacity accordingly: for 100 samples = 3.4 KB; for 500 samples = 17 KB (over the 8 KB DB limit, so use two DBs).
4.2 Sizing math
| Samples | Duration at 100 ms | Bytes (UDT 10) | Fits in one 8 KB DB? |
|---|---|---|---|
| 100 | 10 s | 3 400 | Yes |
| 200 | 20 s | 6 800 | Yes (marginal) |
| 240 | 24 s | 8 160 | No - split into DB100 + DB101 |
| 500 | 50 s | 17 000 | No - multi-DB ring |
The source confirms the typical workload: 100 samples in 10 seconds, well within the 8 KB DB ceiling.
5. Implementing the FIFO (TI-S7 Converting Blocks)
The Siemens STEP 7 Standard Library > TI-S7 Converting Blocks contains purpose-built FIFO functions, originally delivered with the technology CPUs (CPU 31xT, FM 350). They can be installed on any S7-300 / S7-400 and accept ANY pointer inputs, which is exactly the use case described in the source ("treat it as a FIFO stack, use the table functions FIFO-Load").
The two relevant calls are:
- FIFO_Load - pushes a value into the FIFO; returns status EMPTY / FULL / OVERFLOW in RET_VAL and the table-handle word.
- FIFO_Unload - pops the oldest value from the FIFO.
Reference: SIMATIC S7-300 / S7-400 Standard and System Functions - Reference Manual.
5.1 OB35 fragment - push to FIFO
// OB35 - capture PID snapshot
// Inputs from SFB 41 instance DB (e.g. DB50)
L DB50.DBD 24 // PV_IN scaled position, REAL
T MD 200 // snapshot temp REAL
L DB50.DBD 28 // SP_INT
T MD 204
L DB50.DBD 56 // LMN
T MD 208
L DB50.DBD 0 // I_ITVAL (effective error)
T MD 212
CALL SFC 1 // READ_CLK
RET_VAL := MW 220
CDT := MD 224
// Build one UDT 10 record at MW 200..MW 235
// Push it to DB100 via FIFO_Load
CALL "FIFO_Load"
DB_NO := 100
I_DATA := P#M 200.0 BYTE 36
RET_VAL := MW 250
A M 252.0 // status.FULL bit
JC COPY_AND_RESET
6. SFC 20 BLKMOV: Snapshot to OPC Mirror DB
When the FIFO returns FULL, OB35 transfers the entire DB100 to DB200 in a single block-move. SFC 20 "BLKMOV" copies up to 64 KB in one call on the S7-300, but is interruptible by higher-priority OBs. Because the source DB is in the work-memory page table, BLKMOV is fast (a 4 KB block typically completes in < 1 ms on a CPU 312C).
COPY_AND_RESET:
CALL SFC 20 // BLKMOV
SRCBLK := P#DB100.DBX 0.0 BYTE 3400
RET_VAL := MW 260
DSTBLK := P#DB200.DBX 0.0 BYTE 3400
JC ERR_COPY // RET_VAL 0=OK, !=0 error
Error codes:
| RET_VAL (hex) | Meaning | Remedy |
|---|---|---|
| 0000 | No error | - |
| 8091 | Source area invalid / not in work memory | Verify DB100 base, length |
| 8092 | Destination area invalid | Verify DB200 base, length |
| 8xxy | Access error during copy (see manual) | Check DB lengths match |
7. SFC 21 FILL: Resetting the Acquisition Buffer
Immediately after BLKMOV, the FIFO must be cleared so the next 10-second capture window starts from zero. SFC 21 "FILL" writes a constant pattern across the entire DB.
CALL SFC 21 // FILL
BVAL := P#M 0.0 BYTE 4 // zero-pattern (MW0 = 16#0000)
RET_VAL := MW 262
BLK := P#DB100.DBX 0.0 BYTE 3400
// Reset OB35 cycle counter (custom)
L 0
T DB100.DBD 3400 // sample counter
8. SIMATIC NET OPC Server Configuration
The PC side requires:
- A Siemens communications processor (CP 5611 PCI for PROFIBUS / MPI, or CP 5612 for SOFTNET-DP / SOFTNET-PB, or CP 1613 for Industrial Ethernet).
-
SIMATIC NET PC software (currently V18 / V19 / V20 depending on Windows 10 / 11). The install contains:
- NCM PC Manager (PC station configuration)
- OPC Scout V20 (browser for items)
- OPC DA Server (the actual S7 data source)
- S7 OPC Reducer (item filter)
- Configured S7 connection: Station > Add > S7 Connection, partner = CPU 312C rack/slot, slot of OPC server = 1 (default).
- OPC items: DB200,BYTE 0,N exposed as an array of UDT 10 equivalents.
Reference: SIMATIC NET OPC - FAQ and configuration overview (Siemens Online Support entry ID 23485970).
8.1 PC Station topology
[PC Station "DATA_LOGGER"]
|-- [CP 5611] Index 1 - PROFIBUS (MPI can run on CP 5611 with adapter)
|-- [OPC Server] Index 2 - S7 protocol
|-- [Application] Index 3 - WinCC / Excel / third-party
S7 Connection:
Local End = OPC Server
Partner = CPU 312C @ MPI 2 (or PROFIBUS address 2)
Slot = 2
Rack = 0
8.2 Configuring items in OPC Scout
- Open OPC Scout V20.
- Connect to OPC.SimaticNET.
- Add a group "PID_LOG".
- Add an item per DB200 field. Because the array is contiguous, expose it as
S7:[DATA_LOGGER]DB200,BYTE0,3400for bulk read, or expose per-offset itemsS7:[DATA_LOGGER]DB200,REAL0for individual access from VBA.
9. Excel / VBA Integration via OPC DA Automation
Excel can read the OPC items in two common ways:
- OPC DA Automation wrapper - the Siemens-supplied opcdaauto.dll exposes the OPC DA 2.0 spec as a COM object.
- OPC Foundation .NET Standard - using OPCFoundation.NetStandard.Opc.Ua.Client or the UA COM wrapper if the gateway supports UA.
9.1 VBA skeleton (OPC DA)
' Add reference: OPC DA Automation 2.0
Option Explicit
Dim WithEvents opcServer As OPCServer
Dim WithEvents opcGroup As OPCGroup
Dim opcItem As OPCItem
Sub Connect_OPC()
Set opcServer = New OPCServer
opcServer.Connect "OPC.SimaticNET"
Set opcGroup = opcServer.OPCGroups.Add("PID_LOG")
opcGroup.IsActive = True
opcGroup.IsSubscribed = True
opcGroup.UpdateRate = 200
Set opcItem = opcGroup.OPCItems.AddItem( _
"S7:[DATA_LOGGER]DB200,REAL0", 1)
' Bulk-add all 3400 bytes if needed via AddItems()
End Sub
Private Sub opcGroup_DataChange( _
ByVal TransactionID As Long, _
ByVal NumItems As Long, _
ClientHandles() As Long, _
ItemValues() As Variant, _
Qualities() As Long, _
TimeStamps() As Date)
Dim i As Long
Cells(1, 1) = "t_ms"
Cells(1, 2) = "pv_mm"
Cells(1, 3) = "sp_mm"
Cells(1, 4) = "lmn_pct"
For i = 1 To NumItems
Cells(i + 1, 1).Value = ItemValues(i)
Next i
End Sub
9.2 CSV export from Excel
Once the spreadsheet contains the 100-sample window (rows 2-101, columns A-D), save it with ActiveWorkbook.SaveAs "C:\Logs\PID_" & Format(Now,"yyyymmdd_hhnnss") & ".csv", xlCSV. For continuous logging, add a timer-driven copy triggered every 10 s. CSV files open directly in Excel (or any text editor, as the source suggests Word too) without further conversion.
10. Alternative Data Transfer Methods
The OPC route is not the only option. The table below summarises each path against memory, hardware, and Excel-readiness criteria:
| Method | Hardware required | Throughput | Excel-friendly? | Memory budget on CPU | Comment |
|---|---|---|---|---|---|
| SIMATIC NET OPC DA via CP 5611 / CP 5612 | CP card + SIMATIC NET license | Real-time, 100 ms OK | Yes (VBA or 3rd-party) | None (peer-to-peer read) | Reference path; highest reliability |
| PG cable + SAPI-S7 / libnodave / Prodave | USB PC adapter (MPI/PROFIBUS) | ~30 samples/s | Yes (DLL call from C# / Python) | None | Cheap; weak for > 10 Hz logging |
| CP 343-1 Lean / IT + FTP | CP 343-1 IT (6GK7343-1GX31-0XE0) | File push (post-capture) | Yes (CSV) | Minimal | Requires firmware > V2.0 on the CP |
| MMC card + ProSave | STEP 7 ProSave tool | Manual retrieval | Yes (file copy from MMC) | Depends on file length | MMC must be FAT16; up to 8 MB |
| Web server (CPU 31x FW 3.x) | Ethernet CP or PN-CPU | HTTP poll | Indirect (Power Query) | None | CPU 312C cannot run user web pages - need CPU 31x PN/DP |
| Modbus TCP gateway | Modbus CP / 3rd-party | Polled | Yes (VBA winsock) | None | Useful when OPC is not licensed |
10.1 MMC card as a fallback
If the PC hardware is unavailable, the CPU 312C can be configured to write a binary log to its MMC using SFC 82 / SFC 83 / SFC 84 (CREATE / WRITE / CLOSE). The standard MMC limit is 8 MB on the 312C variant. Data is retrieved later via PLC > Copy RAM to ROM in STEP 7 or ProSave on the PC.
10.2 CP 343-1 IT FTP push
With a CP 343-1 IT (6GK7343-1GX31-0XE0) in slot 4, the controller can use FTP_GET / FTP_PUT from the IT-CP library to drop a CSV file on a Windows share or FTP server. The CPU writes the file from a DB image, the FTP block streams it over TCP/IP. This removes the OPC dependency entirely and answers the source's question about "simplest way" to move DB data to the PC.
11. Memory Budgeting for CPU 312C
Work-memory consumption of a typical data-logging build on the CPU 312C:
| Object | Bytes (approx.) | Notes |
|---|---|---|
| SFB 41 instance DB | 2 200 | Includes CONT_C background data |
| OB1 + OB35 + OB100 + PID logic | 3 000-4 000 | Depends on STL vs LAD |
| DB100 FIFO buffer (100 samples) | 3 400 | UDT 10 = 34 bytes + 2 pad = 36 |
| DB200 OPC mirror | 3 400 | Identical layout |
| UDT 10 definition | 0 | Resolved into consuming DBs |
| FIFO system data (per Siemens) | ~ 32 | Header bytes for FIFO_Load |
| Total | ~ 12 000 | Out of 16 KB total |
The remaining ~4 KB is consumed by Siemens system blocks (SFC / SFB copies in work memory). The CPU will tolerate the build but has no headroom for additional alarms, recipe DBs, or future expansion. If the project grows beyond this footprint, either upgrade to CPU 313C-2 DP (32 KB work) or CPU 314C-2 DP (48 KB work). The field report explicitly warns that "what you are asking is memory-intensive, and ressource intensive. It might very well be impossible to do with your machine." - this table quantifies that concern.
12. Verification and Commissioning Checklist
- OB35 trigger rate - Watch CPU Diagnostics Buffer in STEP 7; OB35 entries should appear every 100 ms. Verify the start time delta between consecutive OB35 calls is 95-105 ms (allow jitter).
- FIFO fill rate - Monitor DB100 sample counter; expect +1 every 100 ms.
- FULL flag transition - Set a VAT breakpoint on M 252.0; should pulse every 10 s for a 100-sample FIFO.
- BLKMOV return value - Watch MW 260 in OB35; must read 0000 after the copy.
- FILL return value - Watch MW 262; must read 0000 after the reset.
-
OPC Scout connectivity - Browse
S7:[DATA_LOGGER]DB200,BYTE0; quality should be GOOD and value should change every 10 s. -
Excel DataChange - Single-step the
opcGroup_DataChangeevent; verify Cell(2,1) updates. - File output - Open the saved CSV in Excel; columns A-D populated with 100 rows, pv_mm monotonically tracking cylinder position.
- CPU run-time - Online > CPU > Scan cycle time > OB35; must stay below 50 ms (50% headroom) to avoid trigger skip.
- Free work memory - Module Information > Performance Data > Work Memory > free; must remain > 1 024 bytes after download.
13. Troubleshooting Matrix
| Symptom | Likely cause | Diagnostic | Fix |
|---|---|---|---|
| CPU enters STOP after a few minutes | Work memory exhausted (LOAD/RAM overflow) | SF LED + diagnostic buffer entry "OB load error" | Reduce FIFO depth, upgrade CPU, archive older samples to MMC |
| OB35 skipped cycles | OB35 execution time > scan time | OB35 PY time delta > 100 ms | Move BLKMOV / FILL to OB1; raise OB35 priority |
| FIFO shows OVERFLOW | OPC consumer slower than producer | MW 250 word = 16#8xxx | Increase OB35 time to 200 ms; use subscribed OPC reads |
| OPC items all show quality BAD | MPI / PROFIBUS cable unplugged or wrong baud | CP 5611 diagnostic in NCM PC | Check DIP switches on bus terminator; verify baud matches CPU |
| Excel cells contain 0 / -1.#INF | REAL field misaligned | Compare DB200 offsets against UDT 10 | Add 2-byte pad; reimport DB200 to OPC Scout |
| VBA hangs after 30 min | OPC subscription memory leak | Task Manager | Implement opcGroup.RemoveAllItems and reconnect hourly |
| FIFO data scrambled between blocks | Race between OB1 read and OB35 write | Trace VAT on DB100 header bytes | Add EN_LOG gate; move FIFO Unload to OB1 with one-shot |
| CPU reports "FIFO full" constantly | FIFO_Unload never called | Cross-reference OB1 call to FIFO_Unload | Wire FIFO_Unload to OB1 after BLKMOV ack flag |
14. Summary of Recommended Stack
For the originally requested "100 samples in 10 seconds, exported to Excel" workload on a CPU 312C with SFB 41 PID on a hydraulic axis, the canonical architecture is:
- OB35 at 100 ms sampling
- DB100 FIFO_Load / FIFO_Unload from TI-S7 Converting Blocks (UDT 10)
- SFC 20 BLKMOV at FIFO-FULL to mirror DB200
- SFC 21 FILL to reset DB100
- CP 5611 / CP 5612 + SIMATIC NET OPC DA
- Excel VBA DataChange event to dump rows
- Periodic CSV save with timestamped filename
If the CPU 312C work-memory budget is exhausted, the next preferred alternative is CP 343-1 IT FTP push of the CSV file, which removes the OPC layer and the PC-side SIMATIC NET dependency entirely. Word-format export is also straightforward - the source asks "how can I open it with Excel or Word" - and a CSV file imports cleanly into both applications via File > Open.
FAQ
Can I log at 10 ms instead of 100 ms on a CPU 312C?
Yes, by setting OB35 scan time to 10 000 µs (10 ms) in HW Config. Be aware that the OB35 runtime on CPU 312C is typically 1-3 ms for a small FIFO_Load + PID call; a 10 ms scan leaves thin headroom. Verify with the OB35 PY timestamp delta and confirm no cycle-skip events in the diagnostic buffer.
How much work memory does SFB 41 "CONT_C" consume?
Approximately 1.8-2.2 KB of work memory per multi-instance DB on CPU 312C. Each call also requires one DB number from the 1-511 DB pool and consumes background RAM proportional to its configured cycle time. Reference: SFB 41/42/43 CONT_C/CONT_S/PULSEGEN manual.
Can I read the FIFO directly from Excel without OPC?
Yes, using a third-party SAPI-S7 / libnodave / Prodave MPI driver on the PC side. This avoids the SIMATIC NET OPC license but limits you to synchronous reads (~30 samples/s) and requires custom C/C++/Python glue code instead of VBA.
What is the maximum DB size on CPU 312C?
8 KB (8 192 bytes) per DB, regardless of firmware variant. The total work-memory pool is 16 KB. For longer capture windows, split the buffer across multiple DBs and let the application layer concatenate them, or upgrade to CPU 313C-2 DP (16 KB max DB, 32 KB work).
Is OPC UA an option on this CPU?
No - the S7-300 family does not support OPC UA natively. To expose OPC UA you must install a Siemens SIMATIC NET OPC UA gateway on the PC (version 14+) and use it as a bridge between the S7 DA server and UA clients. Alternatively, an external CP 343-1 PN with firmware 3.x can run a UA server when configured with TIA Portal V16+.