Logging S7-300 Data to MS Access via OPC and WinCC

David Krause14 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

1. Problem Overview and Engineering Context

The requirement is straightforward on paper but ambiguous in the SIMATIC toolbox: a Siemens S7-300 CPU 315-2DP must receive digital feedback signals from two pieces of test equipment (a flow tester and a leak tester), plus a marker machine that prints a serial number on each part, and produce a traceable production record containing:

  • Object serial number (string from the marker machine)
  • Date and time stamp of the test cycle
  • Pass / Fail result of the leak test (Boolean)
  • Pass / Fail result of the flow test (Boolean)
  • Optional: operator ID, recipe number, station ID

SIMATIC Manager itself is a programming environment, not a runtime data archive. There is no built-in "Log to file" or "Log to Access" button in STEP 7 V5.x. The logging path must be constructed from runtime components outside the PLC. This article enumerates every practical path, with the parts, versions, and configuration calls that an integrator can actually execute in the field.

Important constraint: The OP177B HMI panel discussed in the original requirement is a recipe/project storage device, not a data archive. Its MMC is reserved for projects, recipes, and firmware backups. It cannot perform process value archiving, and Siemens documentation explicitly excludes this panel from any WinCC flexible / TIA Logging workflow. Plan the archive tier to live on a PC, not on the HMI.

2. Hardware and Software Prerequisites

Component Specification Notes
PLC S7-300 CPU 315-2DP (6ES7315-2AG10-0AB0 or later) DP port for Profibus, MPI/DP second port on -2DP variants
Firmware V2.6 or later recommended Earlier V2.0 firmware lacks some SFB/SFC extensions
STEP 7 V5.5 + SP2 (or STEP 7 V5.6 for Windows 10/11) Provides DataLog (SFB 116/117) on newer CPUs
PC interface CP 343-1 Lean / CP 343-1 (6GK7343-1CX10-0XE0) or PC adapter USB (6ES7972-0CB20-0XA0) Ethernet preferred; MPI/USB adapter viable for low rate
HMI (replacement) TP/OP 177B PN/DP, KTP1200 Comfort, or PC-based WinCC Runtime OP177B cannot archive; migrate to a Comfort Panel or PC runtime
SCADA / Logging WinCC flexible 2008 SP5 or WinCC V7.x Provides Tag Logging and Alarm Logging runtime databases
OPC bridge KEPServerEX V6, Siemens SIMATIC NET OPC, or Softing S7-OPC Required if SCADA is not used
Database MS Access 2016/2019/365 (32-bit recommended) or SQL Server Express 2019+ Access 64-bit has provider issues with classic OPC DA bridges
Driver stack Microsoft.Jet.OLEDB.4.0 (Access .mdb) or ACE.OLEDB.12.0 (.accdb) Match bitness with the OPC client application
Bitness warning: 32-bit OPC servers cannot host inside a 64-bit process. If KEPServerEX is installed as 32-bit (the common installation), all client code, ODBC drivers, and MS Access ACE providers must also be 32-bit. Mismatched bitness is the #1 cause of "Provider cannot be found" errors in this stack.

3. Architecture Options Compared

Option Path Pros Cons
A PLC → WinCC flexible Runtime → Tag Logging (SQL) → linked MS Access / SQL Server Native Siemens path, time-stamped tags, redundancy WinCC flexible Runtime license required
B PLC → CP 343-1 → OPC DA server (KEPServerEX) → MS Access VBA / .accdb No WinCC, works with any OPC client Third-party server, manual VBA glue
C PLC → CP 343-1 → S7-TCP/IP → libnodave / Snap7 → Python / Excel No commercial licenses, open source DIY reliability, no time sync from PLC
D PLC → SFB 116/117 DataLog → MMC / FTP → CSV → Access import Logs survive PLC power cycle, no PC online required CPU 315-2DP does not natively support SFB 116/117; use S7-1200/1500 if this path is required
E PLC → Comfort Panel → Historical logs to USB / network share Simple, all-in-one Storage size, no real-time DB queries

For the original poster's scenario (a small test cell with discrete digital signals and a marker machine), Option A with WinCC flexible Runtime is the most defensible engineering choice. It is also the path most likely to pass a FAT with the end customer because WinCC is the vendor-supported, documentable component.

4. PLC Programming: Build the Production Record DB

Create a global data block in STEP 7 that mirrors the columns of the eventual MS Access table. Keeping the structure 1:1 eliminates field-by-field mapping in the SCADA layer.

4.1 Data Block Layout (DB 100 - "ProdRecord")

DATA_BLOCK DB 100
TITLE =Production Record Buffer
VERSION : 1.0
  STRUCT
    SerialNumber : STRING[20];   // from marker machine, ASCII
    DateTime     : DATE_AND_TIME;// DT format, 8 bytes BCD
    LeakResult   : BOOL;         // 0 = pass, 1 = fail
    FlowResult   : BOOL;
    OperatorID   : STRING[6];
    Recipe       : INT;          // 0..99
    Station      : INT;          // 1..16
    Trigger      : BOOL;         // rising edge = record ready
    RecordID     : DWORD;        // monotonic counter, 0..2^32-1
  END_STRUCT;
END_DATA_BLOCK

Total DB size = 24 + 8 + 1 + 1 + 8 + 2 + 2 + 1 + 4 = 51 bytes. CPU 315-2DP has 128 KB of load memory and 128 KB of work memory; the DB fits trivially.

4.2 OB1 Fragment: Latch the Test Results

// Latch leak test on rising edge of TestDone_Leak
A     "DI_Leak_TestDone";
FP    "M_Leak_Edge";r>JCN   L_End;r>            

4.3 Time Stamp Source

Do not use a free-running timer in the PLC. Either:

  1. Read the WinCC / OPC client's local PC clock and write it back into DB 100 each cycle (simpler), or
  2. Use SFC 1 "READ_CLK" to fetch the CPU's real-time clock (CPU 315-2DP has a hardware RTC backed by a CR2032 battery).
CALL SFC 1
     RET_VAL := MW 100
     CDT     := DB100.DateTime;

5. WinCC flexible Configuration: Tag Logging and Database Link

WinCC flexible 2008 SP5 uses a Microsoft SQL Server 2005 Express instance installed silently with the runtime. The runtime databases are:

  • <Project>_L — Tag Logging (process values)
  • <Project>_A — Alarm Logging

5.1 Declare the External Tag

In WinCC flexible, open Communication → Tags and add an external tag for each DB 100 field. Set:

Tag Address Type Acquisition
SerialNo DB100.DBB0, 20 bytes String Cyclic 1 s
DateTimeRaw DB100.DBB24, 8 bytes Date/Time (BCD) On change
LeakResult DB100.DBX32.0 Bool On change
FlowResult DB100.DBX32.1 Bool On change
RecordID DB100.DBD44 DWord On change

5.2 Configure the Tag Logging Archive

  1. Open Logs → Tag Logging, add a new archive named ProdArchive.
  2. Add each tag from section 5.1 as a logged value. Choose On change for boolean fields and Cyclic, 1 s for the date/time and serial number.
  3. Set the archive backing to Database (SQL Server). WinCC flexible stores it under C:\ProgramData\Siemens\WinCC flexible\Logs\.

5.3 Connect MS Access to the WinCC SQL Store

From MS Access 2016/365 (32-bit):

  1. Open Access, choose External Data → ODBC Database.
  2. Select Link to the data source by creating a linked table.
  3. Click Machine Data Source and add a new System DSN pointing at SQL Server named WINCC_FLEX pointing to LOCALHOST\WINCCFLEXEXPRESS with Windows authentication.
  4. Select the ProdArchive table; Access creates a linked table mirroring the WinCC schema.

You now have live linked tables. Build Access queries and reports against ProdArchive exactly as you would against a native Access table.

Schema caveat: WinCC flexible names the time field TimeStamp (UTC by default) and the value field RealValue (DOUBLE) or QualityCode (TINYINT). For booleans, 0 = FALSE, 1 = TRUE; for "invalid", QualityCode = 0x40. Filter on QualityCode in production queries.

6. OPC DA Path: Bypass WinCC, Use KEPServerEX

If the project does not justify a WinCC flexible Runtime license, a KEPServerEX (or Siemens SIMATIC NET OPC Server) channel can be read directly from a VBA macro inside MS Access.

6.1 KEPServerEX Channel Setup

  1. Install KEPServerEX V6.4 or later.
  2. Add a new Siemens TCP/IP Ethernet driver. Set IP = the CP 343-1 address, port 102.
  3. Create device S7_300, rack 0, slot 2 (CPU 315-2DP lives in slot 2 of rack 0).
  4. Add tags mapping to the DB 100 offsets defined in section 4.1. Use the DB address mode (e.g., DB100.B0 as a String of 20 chars; DB100.B24 as Date of 8 bytes; DB100.B32.0 and DB100.B32.1 as Boolean).

6.2 MS Access VBA: Read OPC and Append to Local Table

' --- Module: modLogS7 (in MS Access .accdb, 32-bit) ---
Option Compare Database
Option Explicit

' References: OPC Automation 2.0, Microsoft ActiveX Data Objects 6.1

Public Sub PollS7()
  Dim oPC As OPCAutomation.OPCServer
  Dim oGrp As OPCAutomation.OPCGroup
  Dim oItem As OPCAutomation.OPCItem
  Dim iHandles(1 To 5) As Long
  Dim vValues(1 To 5) As Variant
  Dim vQualities(1 To 5) As Variant
  Dim vTimes(1 To 5) As Variant
  Dim cn As ADODB.Connection, rs As ADODB.Recordset
  Dim sSQL As String

  ' 1) Connect to KEPServerEX
  Set oPC = New OPCAutomation.OPCServer
  oPC.Connect "KEPware.KEPServerEX.V6"
  Set oGrp = oPC.OPCGroups.Add("S7Read")
  oGrp.UpdateRate = 500
  oGrp.IsActive = True
  oGrp.IsSubscribed = False

  Set oItem = oGrp.OPCItems.AddItem("S7_300.DB100.STRING20.0", 1)
  iHandles(1) = oItem.ServerHandle
  Set oItem = oGrp.OPCItems.AddItem("S7_300.DB100.DATE.24", 2)
  iHandles(2) = oItem.ServerHandle
  Set oItem = oGrp.OPCItems.AddItem("S7_300.DB100.BOOL.32.0", 3)
  iHandles(3) = oItem.ServerHandle
  Set oItem = oGrp.OPCItems.AddItem("S7_300.DB100.BOOL.32.1", 4)
  iHandles(4) = oItem.ServerHandle
  Set oItem = oGrp.OPCItems.AddItem("S7_300.DB100.DWORD.44", 5)
  iHandles(5) = oItem.ServerHandle

  oGrp.SyncRead OPCAutomation.OPCDevice, 5, iHandles, _
                 vValues, vQualities, vTimes

  ' 2) Append to local Access table tblProduction
  Set cn = CurrentProject.Connection
  sSQL = "INSERT INTO tblProduction " & _
         "(SerialNo, DateTime, LeakResult, FlowResult, RecordID) " & _
         "VALUES (?,?,?,?,?)"
  Set rs = New ADODB.Recordset
  rs.Open sSQL, cn, adOpenKeyset, adLockOptimistic
  rs(0) = CStr(vValues(1))
  rs(1) = CDate(WinCC_BcdToDate(vValues(2)))
  rs(2) = CBool(vValues(3))
  rs(3) = CBool(vValues(4))
  rs(4) = CLng(vValues(5))
  rs.Update
  rs.Close

  oPC.OPCGroups.Remove "S7Read"
  oPC.Disconnect
End Sub

' --- Helper: convert S7 DATE_AND_TIME (BCD) to VBA Date ---
Public Function WinCC_BcdToDate(raw As Variant) As Date
  Dim s As String, p As Integer
  s = ""
  For p = 1 To LenB(raw)
    s = s & Right("0" & Hex(AscB(MidB(raw, p, 1))), 2)
  Next p
  ' Format: YYYYMMDDHHmmss.mmm
  WinCC_BcdToDate = CDate( _
    Mid(s, 1, 4) & "-" & Mid(s, 5, 2) & "-" & Mid(s, 7, 2) & " " & _
    Mid(s, 9, 2) & ":" & Mid(s, 11, 2) & ":" & Mid(s, 13, 2))
End Function

6.3 Local Access Table Schema

CREATE TABLE tblProduction (
  RecordID    LONG          PRIMARY KEY,
  SerialNo    TEXT(20)      NOT NULL,
  DateTime    DATETIME      NOT NULL,
  LeakResult  YESNO         NOT NULL,
  FlowResult  YESNO         NOT NULL,
  OperatorID  TEXT(6),
  Station     INTEGER
);
CREATE INDEX idx_DT ON tblProduction (DateTime);
Polling rate vs. production rate: Calling PollS7 once per cycle is wasteful. Use the rising edge of DB100.Trigger as the start condition. In KEPServerEX, add the trigger tag and check it inside the VBA macro before reading the rest of the buffer.

7. System Topology

The following inline SVG shows a complete Option A + Option B hybrid layout for a single-cell test station.

Flow Tester (digital I/O) Leak Tester (digital I/O) Marker Machine RS-232 serial No. S7-300 / CPU 315-2DP DB 100 ProdRecord OB1: latch tests SFC 1: read RTC CP 343-1 (Ethernet) MPI/DP | PROFINET KEPServerEX Siemens TCP/IP driver OPC DA 2.05 / 3.0 channel = CP 343-1 MS Access .accdb VBA: PollS7() tblProduction Reports, queries Optional: linked SQL Server Express for multi-user access WinCC flex Runtime Tag Logging (optional)

8. Verification and FAT Checks

After commissioning, run the following verification matrix. Each row is a discrete check; sign off each before moving on.

Check Method Pass Criterion
DB 100 fills correctly Online → Monitor/Modify on DB 100 in STEP 7 SerialNo, DateTime, LeakResult, FlowResult all visible after one cycle
OPC tag values match DB KEPServerEX Quick Client, force poll to 100 ms All five OPC items show "Good" quality and the same values as STEP 7
Access row inserted Run PollS7 manually from the Immediate window One new row in tblProduction with non-null SerialNo and DateTime within 1 s of PC clock
Time drift < 1 s Compare DB100.DateTime to PC time in the Access table Drift < 1000 ms, stable over 1 hour
WinCC flex archive WinCC flex Information Server, query ProdArchive Row count grows by one per cycle
PC clock sync Time source from PC, NTP to a domain controller Drift between two cells < 1 s across an 8-hour shift
Power-loss recovery Pull PC plug, restore, restart KEPServerEX and Access No duplicate row on the next cycle; RecordID continues monotonically
Cycle time check Insert "cycle start" / "cycle end" markers in OB1; compute diff in Access query No missing records at the rated station throughput

9. Error Codes and Field Diagnostics

Symptom Likely Cause Diagnostic Fix
OPC quality = Bad CP 343-1 unreachable, wrong IP, PG/PC port blocked Ping CP, check SIMATIC NET channel diagnostics Open TCP/102, set CP to "Use router" only if needed
Access error 3706: Provider cannot be found 32/64-bit mismatch between KEPServerEX and ACE provider Check Access process bitness in Task Manager Install 32-bit Access, or use 64-bit KEPServerEX with 64-bit provider
Time field reads 1990-01-01 CPU RTC battery dead, SFC 1 returns invalid time STEP 7 → PLC → Set Time... Replace CR2032 on CPU 315-2DP, set time from PC
Duplicated rows in Access VBA macro polling on timer without trigger guard Add idempotency: WHERE NOT EXISTS(SELECT 1 FROM tblProduction WHERE RecordID = ?) Switch to trigger-edge polling
WinCC flex archive stops logging SQL Express database full or MDF file > 4 GB WinCC flex Information Server → Archive backup Configure archive backup in WinCC flex, schedule nightly
Marker serial number gibberish Baud rate mismatch or wrong string terminator on RS-232 HyperTerminal, or TIA Comm trace Match baud (9600 / 19200), set CR+LF terminator
Leak/Flow result latches wrong OB1 logic races with new test cycle Force the trigger in monitor mode, observe DB 100 Use FP (rising-edge) bit on TestDone signals, not raw I/O

10. Field-Proven Caveats

  • OP177B cannot archive. If the customer insists on a Siemens panel, the OP177B must be replaced with a TP177B PN/DP (limited, no SQL) or, more practically, a Comfort Panel KTP1200 or TP1500. Comfort Panels can write historical data to a network share or to a SQL Server via the "Audit" or "Log" option.
  • 32-bit MS Access has a 2 GB cap. At 50 bytes/record, that is ~40 million rows. For a single test cell running 24/7 at 1 part per 5 s, this is 6.9 years. For a multi-cell plant, escalate to SQL Server Express from day one.
  • Do not use the S7 date/time BCD as a primary key. Use a monotonic DWORD counter (DB100.RecordID) incremented each cycle. This guarantees uniqueness even if two records share a millisecond.
  • Watch the CP 343-1 connection count. KEPServerEX, WinCC, and STEP 7 can simultaneously open connections. CP 343-1 Lean supports 4 S7 connections total, CP 343-1 supports 8. Run out of connections and the OPC server reports "Out of resources" with WSAENOBUFS (10055).
  • Watchdog timeouts. When a CP is reachable but the PLC is in STOP, OPC quality transitions to Bad. Make sure the VBA macro does not insert a row on a Bad-quality read.
  • Regional settings. Access and WinCC both expect YYYY-MM-DD or the system locale format. Mixing en-US and de-DE installations on the same project corrupts date queries. Set one locale and use ISO format in code.

11. Frequently Asked Questions

Can the S7-300 CPU 315-2DP log directly to MS Access without a PC?

No. The CPU 315-2DP has no file system and no built-in database client. It can only write to load memory (MMC) as project or recipe storage. For MS Access archiving you need a runtime tier: WinCC flexible Runtime, KEPServerEX, or a custom OPC/S7-TCP client running on a Windows PC. S7-1200/1500 with SFB 116/117 DataLog can write CSVs to an MMC or FTP server, but the 315-2DP cannot.

Why does the OP177B not appear as a logging option in WinCC flexible?

OP177B is a key-and-text panel with no Tag Logging runtime component and no expandable log memory. Its MMC card stores projects, recipes, and firmware only. Migrate to a Comfort Panel (KTP1200, TP1500, TP2200) or to a PC-based WinCC flexible Runtime if process value archiving is required.

Which path is cheapest for a 2-station cell: WinCC flex Runtime, KEPServerEX, or Snap7?

KEPServerEX is cheapest for a single PC: a single 8-hour development effort using the free demo (2-hour runtime cap, then restart) or a 4-tag/1-channel KEPServerEX license around USD 600. WinCC flexible Runtime is licensed per HMI station and requires the engineering software. Snap7 + Python is free but you write and maintain the OPC-equivalent glue yourself; for a validated production cell, the maintenance cost typically exceeds the KEPServerEX license.

Do I need CP 343-1, or can the S7-300 reach the PC over MPI?

MPI works for low-volume polling (1 Hz or less) using a PC Adapter USB (6ES7972-0CB20-0XA0) on the PG port. For continuous recording at 5 Hz or higher, use the CP 343-1 over Ethernet. MPI tops out around 187.5 kbit/s on the CPU 315-2DP and shares the bus with any HMI panel you have on the same MPI segment.

How do I get a timestamp accurate to milliseconds from the S7-300?

Call SFC 1 "READ_CLK" to populate a DATE_AND_TIME (8-byte BCD) tag. The format is YYYY-MM-DD-HH-MM-SS-mmm, with the last three BCD bytes giving millisecond resolution. Convert in the OPC client using the helper shown in section 6.2, or use WinCC flexible which auto-converts DATE_AND_TIME to a DATETIME column. Avoid using OB1 scan time as a proxy for ms timestamps; the OB1 cycle on a 315-2DP can drift 5-20 ms.

Back to blog