Siemens S7-1200 DataLog to Excel Export Counter Values via Web

David Krause14 min read
S7-1200SiemensTutorial / 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

The Siemens SIMATIC S7-1200 CPU family (firmware V4.0 and later) supports native data logging through the DataLog instruction set and the integrated web server. A counter value, regardless of whether the source is a high-speed counter (HSC), a CTU/CTD/CTUD IEC counter, or an arithmetic total, can be appended to a CSV-formatted file inside the PLC's load memory. The file is then downloadable from the CPU's web page as a standard comma-separated values file, which opens directly in Microsoft Excel, LibreOffice Calc, or any spreadsheet tool without conversion, parsing, or scripting.

This approach replaces fragile serial protocols, OPC bridges, or PC-side polling. There is no PC application required at runtime, no HMI runtime license involved, and no scripting layer. Once the PLC is on a routable IP address with the web server enabled, the data can be retrieved from any browser on the network.

Retention is local to the PLC. If the application must preserve counter totals across a power cycle or after the user resets the counter to zero, the running total must be written to a retain tag (global DB with retain attribute set) and the DataLog file must be closed properly before power-off, or the S7-1200's internal maintenance mechanism will finalize the file automatically when the PLC goes to STOP.

Prerequisites

/DataLogs on the SD card when inserted
Component Required Version / Specification
CPU S7-1200 any model (CPU 1211C / 1212C / 1214C / 1215C / 1217C); firmware V4.0 or higher is required for DataLog and standard web server CSV download
Firmware V4.2 minimum recommended for stable DataLog behavior; V4.4 or V4.5 recommended for production lines
TIA Portal V13 SP1 Update 9 or higher; V15.1, V16, V17, or V18 / V19 / V20 (matching the CPU firmware)
Load memory
Network Ethernet PROFINET interface configured with a fixed IP (DHCP is acceptable for discovery but not for production)
HMI (optional) Comfort Panel, Basic Panel, WinCC Runtime Advanced, or Unified PC Runtime for the export button

How the S7-1200 DataLog Mechanism Works

The S7-1200 maintains DataLog files as plain CSV files in the /DataLogs/ directory of the load memory. The runtime system writes one row per DataLogWrite call and persists the file using a wear-leveled write pattern suited to the SD card. The header row is defined when the file is created with DataLogCreate. Subsequent rows may contain any number of columns, and each column maps to a tag address passed into the DataLogWrite instruction.

Instruction Purpose
DataLogCreate Creates a CSV file with a defined name, header columns, and data format (overwrites if existing)
DataLogWrite Appends one row to an open DataLog
DataLogClose Closes an open DataLog and finalizes it for download
DataLogOpen Re-opens a previously created DataLog for further writes
DataLogDelete Deletes a DataLog file from load memory
DataLogNewFile Closes the current DataLog and creates a new file (rotates by size or count)

Step 1 — Configure the Web Server in the CPU

The CPU web server is the access point for downloading CSV files. Enable it from the Device Configuration of the S7-1200 in TIA Portal.

  1. Open the project and select the S7-1200 CPU in the project tree.
  2. Open Device View and select the CPU module.
  3. In the Properties pane, navigate to Web server (Webserver).
  4. Tick "Enable web server on this module".
  5. Select "Permit access only via HTTPS" if the network is exposed; otherwise, HTTP is acceptable on a closed industrial LAN.
  6. Under Users, define at least one user with the right "Read files" (and optionally "Write files" for deletion). The admin user has all rights by default but requires a password; configure a strong password (8+ characters, alphanumeric + symbol).
  7. Under Automatic update, set the web page refresh interval to "None" or "5 s" depending on operator preference.
  8. Compile and download the hardware configuration to the PLC.

After download, browse to http://<cpu-ip>/. The standard web page exposes a "File browser" or "DataLogs" link once at least one DataLog has been created by the program. For full details on web server security options, see the S7-1200 System Manual chapter "Web Server".

Step 2 — Build the Counter and the Persistent Total DB

The application described in the field report requires three pieces of information per batch: total chickens counted, number of counter resets, and a timestamp. The counter value itself can come from a physical digital input wired to a photoelectric sensor, or from an HSC configured on the CPU.

Create a global data block named DB_Production with the following structure. Mark every tag as RETAIN on the DB properties so that values survive a power loss or a STOP-to-RUN transition.

[DB_Production] // RETAIN = TRUE
  Production: ARRAY[0..15] OF STRUCT
    Timestamp         : DTL;          // 12 bytes; set with T_CONV / system clock
    TotalCount        : DINT;         // running counter, can exceed INT limit
    ResetCount        : INT;          // how many times the operator reset
    BatchID           : INT;          // incrementing batch identifier
    Operator          : STRING[16];   // optional operator name
    LastReset         : DTL;          // last reset timestamp
  END_STRUCT;
  CurrentIndex       : INT;          // current row, wraps at 16
  HSC_CounterValue   : DINT;         // input from HSC ID 0
  Counter_PV         : INT;          // preset value for reset trigger
  ResetRequest       : BOOL;         // HMI button
  DataLogBusy        : BOOL;         // status of DataLogWrite
  DataLogError       : WORD;         // error word from instruction
END_DB

Step 3 — Implement the DataLog in OB1 (or a Cyclic OB)

Place the DataLog instructions in Main [OB1] or, for better determinism, in a Cyclic interrupt OB (e.g., OB200). The example below uses a rising-edge trigger on the HSC's new-value flag to record a row for every counted item, and a second trigger on ResetRequest to record a reset event.

3.1 One-time initialization

// Network 1: First scan — create DataLog
IF "FirstScan" THEN
    "DataLogCreate_DB"(REQ := TRUE,
                        RECORDS := 16,
                        NAME := 'ChickenLog',
                        ID := "DataLogID",
                        HEADER := 'Timestamp,TotalCount,ResetCount,BatchID',
                        FORMAT := 0,            // 0 = CSV with header
                        ERROR => "DataLogError");
END_IF;

3.2 Append a row on each count event

// Network 2: Detect new count event (e.g., HSC CV = NEW or
//            rising edge on a digital input mapped to HSC ID 0)
IF "HSC_CounterValue" <> "HSC_LastValue" THEN
    "DB_Production".TotalCount := "HSC_CounterValue";
    "DB_Production".Timestamp  := RD_SYS_T;

    "DataLogWrite_DB"(REQ := TRUE,
                       ID := "DataLogID",
                       Timestamp := "DB_Production".Timestamp,
                       DATA := "DB_Production".TotalCount,
                       DONE  => "DataLogBusy",
                       ERROR => "DataLogError");
    "HSC_LastValue" := "HSC_CounterValue";
END_IF;

3.3 Append a row on reset

// Network 3: Operator reset event
IF "ResetRequest" THEN
    "DB_Production".ResetCount := "DB_Production".ResetCount + 1;
    "DB_Production".LastReset  := RD_SYS_T;
    "DataLogWrite_DB"(REQ := TRUE,
                       ID := "DataLogID",
                       DATA := "DB_Production".TotalCount,
                       ERROR => "DataLogError");
    "HSC_CounterValue" := 0;
    HSC_0_CTRL := HSC_0_CTRL & 16#FFFE;  // clear HSC CV via CTRL instruction
    "ResetRequest" := FALSE;
END_IF;

The behavior matches the original request: the counter value is captured before the user resets it to zero, so historical rows in the CSV remain valid even though the live counter on the HMI shows zero.

Step 4 — Rotate or Close the DataLog to Allow Download

The web server can only serve closed DataLog files. An open file is still being written to and will not appear in the download list. Two practical patterns:

  1. Periodic rotation: call DataLogNewFile on a timed trigger (e.g., once per hour, once per shift, or when the file exceeds N records). The closed file becomes immediately downloadable.
  2. Manual close via HMI button: use the configuration described in Step 6 to allow an operator to close and reopen the file on demand.
// Network 4: Close & rotate when file size threshold reached
IF "RecordCount" >= 1000 THEN
    "DataLogClose_DB"(REQ := TRUE,
                       ID := "DataLogID",
                       DONE => "DataLogBusy");
    "DataLogNewFile_DB"(REQ := TRUE,
                          ID := "DataLogID",
                          NAME := 'ChickenLog',
                          ERROR => "DataLogError");
    "RecordCount" := 0;
END_IF;

Step 5 — Download the CSV from the Web Server

  1. Open a browser and navigate to http://<cpu-ip>.
  2. Log in with the configured user (default admin password is empty unless set).
  3. Click "File browser" or "DataLogs".
  4. Locate ChickenLog.csv in the list.
  5. Right-click and Save As to download the file locally.
  6. Open in Excel: File → Open → Browse, set the file type filter to Text Files (*.csv; *.txt), then choose the file. Excel will run the Text Import Wizard; select Comma as the delimiter and General column format.

The downloaded CSV opens cleanly in Excel with the header row pre-populated, each row representing one event (count or reset). For scheduled downloads, the operator can bookmark the direct file URL http://<cpu-ip>/DataLogs/ChickenLog.csv; some browsers cache, so a ?<timestamp> cache-buster is sometimes needed.

Step 6 — Adding the "Export Button" on the HMI

The field report asks specifically whether an export button can be added so the operator can trigger the export before the counter resets. The cleanest implementation:

  1. On the HMI, place a button labeled "Export to Excel".
  2. Configure the button with the event "Click" → "SetBit" on the PLC tag ExportRequest.
  3. In the PLC, when ExportRequest rises, run DataLogClose followed by DataLogOpen with the same NAME. This finalizes the current CSV and reopens it for further writes.
  4. Provide a second button or a screen link to http://<cpu-ip>/DataLogs/ChickenLog.csv on the HMI. Comfort Panels and Unified Panels can launch an embedded browser via the "Browser" control or an Internet Explorer-based element. Basic Panels cannot host a browser; in that case, instruct the operator to scan the IP from a PC.
  5. As an alternative to manual download, configure the PC side to poll the URL every N seconds using wget, PowerShell Invoke-WebRequest, or a scheduled task and append the CSV rows into a master Excel workbook.
// Network 5: HMI Export button handler
IF "ExportRequest" AND NOT "ExportRequest_Old" THEN
    "DataLogClose_DB"(REQ := TRUE,
                       ID := "DataLogID",
                       DONE => "DataLogBusy");
    "DataLogOpen_DB"(REQ := TRUE,
                      MODE := 'WRITE',
                      NAME := 'ChickenLog',
                      ID := "DataLogID",
                      ERROR => "DataLogError");
    "ExportRequest" := FALSE;
END_IF;
"ExportRequest_Old" := "ExportRequest";

Step 7 — TIA Portal Project Engineering Checklist

Before downloading the project to the PLC, validate the following:

  • PLC tag types: the tag passed to DataLogWrite DATA must be one of BOOL, INT, DINT, REAL, STRING, or a DTL timestamp. Mixing types in one row requires separate calls or a structured approach.
  • Header row: define the header at creation time; later rows inherit column widths from the header.
  • RETAIN attribute: enable RETAIN on the production DB so totals survive power cycles.
  • Memory card: if an SD card is inserted, DataLog files are stored there; without a card, the internal load memory is used and capacity is limited (typically 1–4 MB on smaller CPUs).
  • Clock: set the CPU clock via NTP or a master clock to keep timestamps accurate. Use RD_SYS_T for the local time-of-day.
  • Watchdog: the DataLog instructions are non-blocking; ensure REQ is held only until DONE or ERROR rises, otherwise repeated writes may be issued.

For the official TIA Portal information system reference, see Help on the information system - TIA Portal and the TIA Portal online help for context-sensitive F1 documentation.

Error Codes and Diagnostics

DataLogError (hex) Meaning Corrective Action
0000 No error —
0001 DataLog not found Run DataLogCreate first or correct the NAME string
0002 DataLog already open Close before reopening; check for re-entrant calls
0003 DataLog closed by user Re-open with DataLogOpen
0005 DataLog full / memory full Insert larger SD card, rotate with DataLogNewFile, or delete old files
0007 Invalid DATA pointer / wrong type Verify the DATA parameter symbol; multi-row writes must use a contiguous area
0008 Header too long Header is limited; shorten or split into multiple DataLogs
000A Name too long DataLog name is limited to ~24 characters; shorten and ensure uniqueness
8010 File system error Re-seat SD card; check CPU diagnostics buffer; format the card from TIA Portal
8011 Permission denied User lacks "Write files" right; adjust web server user settings

Live diagnostics are also visible in TIA Portal → Online → Diagnostics → DataLogs and in the CPU's Diagnostic buffer via Online → Diagnostics → Diagnostic Buffer.

Verification Procedure

  1. Download the project and place the CPU in RUN.
  2. Trigger a known number of counts (e.g., manually pulse the HSC input 10 times).
  3. Trigger the HMI export button.
  4. Open the CSV in Excel. Confirm TotalCount = 10 and the ResetCount column has incremented on the reset row.
  5. Power-cycle the PLC. After restart, TotalCount and ResetCount in the DB must still show the pre-power-loss values (RETAIN verification).
  6. Browse to the web server and confirm the CSV appears in the File browser pane.
  7. Compare the CSV row count against the RecordCount in the DB; mismatch indicates lost writes during a power loss.

Troubleshooting Matrix

Symptom Likely Cause Fix
Web page shows "DataLogs empty" No DataLog has been created yet, or file is still open Run the program once to trigger DataLogCreate; close with DataLogClose
Browser returns 404 on /DataLogs CPU firmware below V4.0 or web server not enabled Upgrade firmware or enable web server in device configuration
CSV file shows garbage characters Opened directly in Excel instead of via Text Import Wizard Use File → Open → Text Files; set Comma delimiter
Counter resets to 0 before export Reset triggered before DataLogWrite Use a non-blocking write; write BEFORE zeroing HSC
Lost data after power cycle DB not RETAIN or DataLog not closed Set RETAIN on DB; rely on automatic finalization, or add UPS
HMI button has no effect HMI tag not linked to PLC tag, or area pointer disabled Check HMI connection in "Connections" editor; recompile HMI
DataLogError = 0005 (full) SD card exhausted Rotate files, archive old logs to PC, replace SD card with larger one
Browser cannot resolve hostname Only IP works because DNS missing Use direct IP or add entry to hosts file
Timestamps off by hours CPU time zone or DST not set Set time zone in Device Configuration → Time of Day

Alternative Architectures

Option When to Use Trade-Off
DataLog + Web Server (this article) Low to medium volume, no PC at line, manual or scheduled export No real-time streaming; web server CPU overhead
OPC UA server on S7-1200 Real-time SCADA / MES integration Firmware V4.4+ required; more configuration
Modbus TCP / S7 communication to a PC script Custom Python / VB / PowerShell data pipeline PC required; more development effort
SMTP / e-mail from PLC Small daily summaries by e-mail Limited message size; not for high-rate data
FTP push from S7-1200 Automatic upload to a server S7-1200 does not natively push FTP; requires S7-1500 or a relay PC

Field-Proven Caveats

  • Each DataLogWrite consumes flash write cycles. Continuous high-rate logging (more than ~1 write/second sustained) will shorten SD card life; use a high-endurance industrial SD card rated for S7-1200 use (Siemens 6ES7 954-8LF03-0AA0 or equivalent).
  • The web server is single-threaded; concurrent downloads during heavy logging can stall the page. For production lines, schedule downloads during planned downtime.
  • If the counter's preset value is configurable from the HMI, expose it as a tag (e.g., Counter_PV in DB_Production) so the operator can change the reset threshold without a TIA Portal download.
  • When more than 16 columns are needed, use multiple DataLogs or pre-aggregate values into a single string before writing. Each DataLogWrite call writes one row; multi-column rows are constructed by passing a structured tag.
  • When the same DataLog must be read by Excel from multiple PCs simultaneously, serve the file via a network share on a PC that periodically wgets the CSV from the CPU.
  • The S7-1200 web server does not require a TIA Portal license to access at runtime — only the engineering station that configured it does.

Summary Workflow

  1. Enable the CPU web server and create a user with file access rights.
  2. Build a global DB with RETAIN for the counter total, reset count, and timestamps.
  3. Use DataLogCreate on first scan to initialize the CSV with a header row.
  4. Use DataLogWrite on every count and every reset to append rows.
  5. Provide an HMI export button that calls DataLogClose + DataLogOpen.
  6. Download ChickenLog.csv from the CPU web page and open in Excel.

This pattern delivers a robust, vendor-supported, and license-free data export from the S7-1200 without a PC application. For the canonical TIA Portal reference, see Help on the information system - TIA Portal and the TIA Portal online help.

What firmware version does the S7-1200 need to support DataLog?

Firmware V4.0 or higher is required. V4.2 or later is recommended for production stability. Older V3.x firmware does not support the DataLog instruction set.

Can I export the counter values to Excel without a PC application running?

Yes. The S7-1200 web server hosts the CSV file directly. Browse to http://<cpu-ip>/DataLogs/<filename>.csv from any browser and save the file. Excel opens it via the Text Import Wizard with comma as the delimiter.

How do I keep the counter total after the operator resets it to zero?

Mark the global DB as RETAIN in its properties. Add a separate TotalCount tag that increments on every count event and is never reset; the visible counter on the HMI is then a second tag that does get reset.

Why does my CSV not appear in the web server "DataLogs" folder?

The file is only downloadable after DataLogClose has been called. Add an automatic close trigger (periodic rotation, size threshold, or HMI button) so the file finalizes and becomes visible to the browser.

Can the S7-1200 push the CSV directly to a network share or FTP server?

No. The S7-1200 does not support native FTP push or SMB client. Use the web server for pull-based downloads, or move to an S7-1500 if push-based upload is required. A relay PC running a scheduled wget or PowerShell script is the typical workaround.

Back to blog