S7-1200 Data Logging: Configuring CSV Export via Web Server
The SIMATIC S7-1200 CPU integrates a native data logging engine that stores process values to comma-separated value (CSV) files on the controller's internal flash or on an optional SIMATIC Memory Card (SMC). Like the legacy S7-200 datalog routine, the S7-1200 implementation does not require an external HMI, SCADA node, or file server: the CPU owns the file system, the records, and the download interface. Engineers point a web browser at the controller, click the data log link, and pull the CSV directly into Microsoft Excel, OpenOffice Calc, MATLAB, or Python pandas. This makes the S7-1200 data log the lowest-cost historical recorder in the SIMATIC family and the right answer for small machines, remote panels, and commissioning diagnostics where a full SCADA layer is not justified.
This reference walks through the entire flow: program block construction in TIA Portal, web server activation, file management, and field-proven diagnostics. The authoritative specification for limits, instructions, and status codes is the S7-1200 Programmable Controller System Manual; refer to the chapter covering data logging for the firmware revision loaded on your specific CPU.
Overview of the S7-1200 Data Logging Function
S7-1200 data logging is implemented as a set of operations that the user program calls. The CPU maintains a directory of data log files in its load memory; each file has a name, a fixed column header, and a record structure. The user program triggers writes on the desired sample rate, the CPU appends records to the file, and the engineer retrieves the file via the integrated web server. The function is supported on every S7-1200 CPU model from CPU 1211C through CPU 1217C, including the second-generation S7-1200 G2 devices released with firmware V4.5 and later.
Use cases in the field include:
- Long-term process trending when a permanent HMI is not installed.
- Alarm and event recording for post-incident analysis on unattended equipment.
- Energy, flow, or batch data capture where a regulatory retention period applies.
- Commissioning diagnostics where the laptop must recover the trace from the controller directly.
- OEM test stands that ship a one-month operating record back to engineering with the unit.
The output file is a standard CSV with a header row. It opens in Excel without any conversion step, which is the primary reason engineers prefer the S7-1200 data log over the S7-1500 trace or a custom block-based solution: no proprietary format, no import wizard, no add-in license.
Prerequisites, Storage Targets, and Firmware Limits
Before writing the first line of code, confirm the following prerequisites. Limits in the S7-1200 data log have changed across firmware revisions; verify the values for your specific build against the Siemens Industry Online Support entry for your CPU.
| Item | Requirement / Limit | Notes |
|---|---|---|
| CPU firmware | V2.0 or later (basic DataLog functions). V4.0 adds DataLogClear. V4.4 and V4.5 expand record and column counts. | Check the CPU's online diagnostics or the device label for the firmware version. |
| Programming software | STEP 7 Basic in TIA Portal V11 SP2 or later. Current TIA Portal V18 or V19 recommended. | Older portals do not show all function block variants. |
| Number of data logs | Up to 8 data logs simultaneously on the CPU. | Includes opened and closed data logs; closed files still occupy a slot. |
| Records per data log | Up to 65,534 records per file (16-bit record counter). | Use DataLogNewFile to start a new file when the count is reached. |
| Columns per record | Up to 64 data columns (firmware-dependent; later firmware allows more). | Each column is a tagged element of a STRUCT or a UDT. |
| Storage target | Internal load memory (small, ~2 MB usable) or SIMATIC Memory Card (SMC) up to 32 GB. | Insert the SMC before the first write. SD cards must be formatted FAT32. |
| SMC types | SIMATIC S7-1200 SMC (4 MB, 12 MB, 24 MB, 256 MB, 2 GB, 32 GB variants). | Third-party SD cards work for storage but do not support the program transfer or firmware update functions. |
| Web server | CPU must have web server activated in device configuration. | HTTPS is supported on firmware V4.0 and later. |
| Network access | Ethernet interface on CPU; static or DHCP IP; port 80 (HTTP) or 443 (HTTPS). | Verify routing if the CPU is behind a managed switch or NAT. |
The internal load memory of the S7-1200 is small. Plan on the SMC for any data log that exceeds a few thousand records; treat the internal memory as scratch space for the most recent operating window. The SIMATIC S7-1200 SMC is hot-swappable when the CPU is in STOP, but not in RUN. Plan shut-down windows for physical media replacement.
Data Log Concepts: File Structure and Lifecycle
Each data log is a CSV file with the following structure on the storage medium:
Timestamp;Press_PSIG;Flow_GPM;Temp_C
2024-06-12 08:00:01.234;12.45;2.31;68.2
2024-06-12 08:00:02.234;12.48;2.30;68.3
2024-06-12 08:00:03.234;12.51;2.32;68.2
The header row is fixed when the data log is created. The CPU appends one record per DataLogWrite call. Timestamps use the CPU's local time-of-day; the format is configurable between the S7 date-and-time representation and an ISO-style string. The S7-1200 writes the file as comma-delimited text with a CRLF line ending, which is the format Excel expects on import.
The lifecycle of a data log is:
- Create with DataLogCreate. Allocates the file, writes the header, returns a 32-bit data log ID.
- Open with DataLogOpen. Required before the first write or after a power cycle, because the CPU closes all data logs on STOP-to-RUN or power loss.
- Write with DataLogWrite. Appends a record. Triggered on a cyclic OB, a time-of-day interrupt (OB10), or a process event.
- Close with DataLogClose. Optional during normal operation; the CPU auto-closes on shutdown.
- New file with DataLogNewFile. Closes the current file, starts a new file with the same name and an incrementing suffix.
- Delete with DataLogDelete. Removes the file from the load memory or SMC.
The CPU automatically closes all data logs on transition from RUN to STOP, on power down, and on warm restart. The data log survives a power cycle only if the CPU has buffered the write to non-volatile memory. Firmware V4.0 and later buffer the most recent write to the SMC, so records in flight at the moment of power loss are preserved. On the internal flash, write buffering is more limited; treat the SMC as the durable storage target for any record that must survive a power cycle.
Building the Data Log Program in TIA Portal
The data log function is implemented as a set of instructions in the user program. Add them to a function block (recommended) or directly in OB1 (acceptable for simple applications). The TIA Portal instruction list under "Extended instructions > Data log functions" exposes six function blocks:
- DataLogCreate — Allocates the data log file and writes the header.
- DataLogOpen — Opens an existing data log for append.
- DataLogWrite — Appends a record to the open data log.
- DataLogClose — Closes the open data log.
- DataLogNewFile — Closes the current file and starts a new file with the same name plus a sequence number.
- DataLogDelete — Deletes a data log file from the load memory or SMC.
- DataLogClear — Empties an existing data log without deleting the file. Available on firmware V4.0 and later.
Each instruction is invoked through a single-instance function block DB. Drag the instruction from the task card onto a network; TIA Portal auto-generates the instance DB. The instance DB stores the REQ edge memory and the status outputs.
Step 1: Define the Record Structure as a Data Block or PLC Data Type
The record structure is a STRUCT that the user program populates before calling DataLogWrite. Define it once as a global DB or a PLC data type (UDT) and reference the same structure in every block that needs the data. Example definition in a global DB named "ProcessData":
DATA_BLOCK "ProcessData"
{ S7_Optimized_Access := 'TRUE' }
VERSION : 0.1
NON_RETAIN
STRUCT
Press_PSIG : REAL; // 0.0 .. 300.0
Flow_GPM : REAL; // 0.0 .. 500.0
Temp_C : REAL; // -40.0 .. 200.0
CycleCount : DINT; // 0 .. 2^31-1
END_STRUCT;
END_DATA_BLOCK
All tags must be elementary data types (BOOL, INT, DINT, REAL, WORD, DWORD, BYTE, CHAR, STRING, DTL, TIME, DATE, TIME_OF_DAY). Arrays and nested structs are not supported in the data log record. If you need to log an array, flatten it into sequential scalar tags of a STRUCT, or log the individual scalars across multiple data log files.
Step 2: Create the Data Log Once on Cold Start
Call DataLogCreate from the startup OB (OB100) on the first scan, or guard the call with a "first run" flag. The instruction must run only once; re-running it on every scan produces a status code 0x8001 (data log already exists). Sample code in Structured Text:
// In FB "DataLogManager" or OB100
IF "FirstScan" THEN
"iDataLogCreate"(REQ := TRUE,
NAME := 'PressTrend',
ID := "DataLogID",
HEADER := 'Timestamp;Press_PSIG;Flow_GPM;Temp_C;CycleCount',
DATA := "ProcessData",
TIMESTAMP := TRUE);
IF "iDataLogCreate".DONE THEN
"DataLogCreateOK" := TRUE;
"iDataLogOpen"(REQ := TRUE,
ID := "DataLogID",
MODE := 'A'); // 'A' = append, 'W' = write (overwrite)
ELSIF "iDataLogCreate".ERROR THEN
"DataLogLastStatus" := "iDataLogCreate".STATUS;
// Capture status for HMI alarm
END_IF;
END_IF;
The MODE parameter on DataLogOpen takes 'A' for append (the usual case) or 'W' for write, which discards existing data and starts at the top. The instruction returns a 32-bit ID in the ID output that subsequent instructions reference. Store that ID in a non-retentive or retentive tag depending on whether you want to resume after a warm restart.
Step 3: Trigger DataLogWrite on a Cyclic or Event Basis
Use a time-of-day interrupt (OB10) for fixed-interval recording, or a cyclic interrupt (OB30..OB38) for sub-second sampling. Edge-trigger the REQ input so each call produces a single record. Latch REQ in the instance DB until the DONE or ERROR bit returns; otherwise the function will attempt to write on every scan and consume the entire cycle budget.
// In OB30 (cyclic interrupt, e.g. 1 s) or a 1-Hz clock from OB10
// Populate the record from process tags first
"ProcessData".Press_PSIG := "ai_Pressure".ScaleValue;
"ProcessData".Flow_GPM := "ai_Flow".ScaleValue;
"ProcessData".Temp_C := "ai_Temp".ScaleValue;
"ProcessData".CycleCount := "ProcessData".CycleCount + 1;
"iDataLogWrite"(REQ := TRUE,
ID := "DataLogID",
DATA := "ProcessData");
IF "iDataLogWrite".DONE OR "iDataLogWrite".ERROR THEN
"iDataLogWrite".REQ := FALSE; // Edge reset
END_IF;
IF "iDataLogWrite".ERROR THEN
"DataLogLastStatus" := "iDataLogWrite".STATUS;
END_IF;
Best practice is to use a handshaking pattern: set REQ, wait for DONE, reset REQ. Forgetting the reset is the single most common cause of "my data log fills up in minutes" support tickets.
Step 4: Rotate Files with DataLogNewFile
When the record count approaches the 65,534 record limit, call DataLogNewFile to close the current file and start a new one with the same root name and an incrementing sequence suffix. A typical pattern is to issue DataLogNewFile daily at midnight using OB10, or when the record count crosses a threshold (e.g. 60,000):
IF "RotateTrigger" THEN
"iDataLogNewFile"(REQ := TRUE, ID := "DataLogID");
IF "iDataLogNewFile".DONE THEN
"RotateTrigger" := FALSE;
END_IF;
END_IF;
The CPU keeps the closed file on the storage medium; download it before the SMC fills. Implement a retention policy that deletes the oldest file with DataLogDelete, or use a scheduled Windows task on an engineering station that pulls files via the web server and clears local copies.
Enabling the Web Server for CSV Download
Data log CSV files are exposed only through the CPU's web server. The web server is disabled by default on the S7-1200 for security reasons; activate it deliberately in the project configuration.
- In the TIA Portal project tree, select the S7-1200 CPU and open Properties > Web server (HTTP/HTTPS).
- Check Enable Web server on this module.
- Select Permit access only with HTTPS for production deployments. HTTPS is available on firmware V4.0 and later; older firmware falls back to plain HTTP.
- Under User management, add at least one user with the right Data log permission. The default "admin" user has full rights but ships with no password on older firmware; assign a strong password on first commissioning.
- Compile the hardware configuration and download to the CPU. The web server starts automatically on the next RUN-to-RUN transition or power cycle.
- Confirm the IP address in Properties > Ethernet addresses > IP protocol. The CPU's IP appears on the web server introduction page for easy access.
Downloading CSV Files from the Web Server
Open a browser and navigate to the CPU's IP. The S7-1200 web server landing page presents navigation entries for diagnostics, identification, module information, communication, and data logs. Click the Data Logs entry. The data log page lists each data log file with its size, record count, modification time, and download button. Click the download icon next to the file you want; the browser saves the CSV to the local download folder.
The default URL pattern is:
http://<CPU-IP>/DataLog.html # file list
http://<CPU-IP>/datalog/PressTrend.csv # direct file access
On HTTPS-enabled CPUs, the corresponding URLs are:
https://<CPU-IP>/DataLog.html
https://<CPU-IP>/datalog/PressTrend.csv
If the user does not have the Data log permission, the file list returns 403 Forbidden. The browser prompts for credentials when the user database is enabled. The web server does not stream records; it always returns the entire file. Plan downloads for the SMC-free period when the CPU is idle, or schedule them off-shift, to minimize latency for other web server users.
For automated retrieval, use a script with HTTP basic authentication:
# PowerShell snippet to pull the latest data log
$cred = Get-Credential
$uri = "http://192.168.0.10/datalog/PressTrend.csv"
Invoke-WebRequest -Uri $uri -Credential $cred -OutFile "C:\Logs\PressTrend.csv"
# Python equivalent
import requests
from requests.auth import HTTPBasicAuth
url = 'http://192.168.0.10/datalog/PressTrend.csv'
resp = requests.get(url, auth=HTTPBasicAuth('admin', 'password'), timeout=10)
open('PressTrend.csv', 'wb').write(resp.content)
Verify the file's CRLF line endings are preserved; some editors on macOS and Linux convert to LF on save, which breaks Excel's import wizard.
Importing the CSV into Excel and Other Tools
Microsoft Excel handles the S7-1200 CSV natively. Double-click the file in Explorer; Excel opens it in a new workbook with each column correctly mapped. The Timestamp column imports as text because the S7-1200 outputs it as a string. To convert timestamps into Excel date values, use Data > Text to Columns on the timestamp column, select the format YMD HMS, and Excel parses it into a real datetime cell.
For larger files (>1 million rows) use Power Query:
- Open Excel, Data > Get Data > From File > From Text/CSV.
- Select the file. Power Query detects the delimiter and column types.
- Click Transform Data, change the Timestamp column to type DateTime, and click Close & Load.
For Python analytics, pandas reads the file with one call:
import pandas as pd
df = pd.read_csv('PressTrend.csv', sep=';', parse_dates=['Timestamp'])
print(df.describe())
The semicolon separator is preserved as-is; do not change it in the CPU. The S7-1200 emits a semicolon because the comma would collide with the default German decimal separator. On US/UK locale workstations, the import wizard must be set to semicolon delimiter.
File Management, Rotation, and Memory Card Sizing
The S7-1200's internal load memory is small (a few MB usable) and is shared with the user program. Any non-trivial data log belongs on the SMC. Sizing the SMC requires three calculations:
- Bytes per record: sum of the byte widths of every column, plus 24 bytes for the timestamp string and CRLF, plus 1 byte per semicolon separator.
- Records per day: sample rate (Hz) × 86,400 seconds/day.
- Bytes per day: bytes per record × records per day.
Example sizing for a 4-column data log with 4-byte REAL values, sampled at 1 Hz:
Bytes per record = 24 (timestamp) + 1 (;) + 4 (Press) + 1 (;) + 4 (Flow) + 1 (;) + 4 (Temp) + 1 (;) + 4 (Cycle) + 2 (CRLF) = 44 bytes
Records per day = 1 Hz × 86,400 s = 86,400 records
Bytes per day = 44 × 86,400 = 3,801,600 bytes ~ 3.8 MB/day
A 30-day retention window requires 114 MB. The 256 MB SMC fits with overhead. For a 100 Hz sample rate on the same record structure, the daily footprint is 380 MB; a 32 GB SMC supports roughly 84 days of continuous recording.
Industrial SD cards have write-endurance limits. Consumer-grade cards typically survive 1,000 to 10,000 write cycles per cell. The S7-1200 does not perform wear leveling, so the same flash cells absorb the append traffic. For continuous logging applications, specify an industrial-grade SMC from Siemens rather than a third-party card. The SMC also supports the S7-1200 firmware update and program transfer functions that consumer cards do not.
Troubleshooting: Status Codes and Field-Proven Fixes
Status codes are returned in the STATUS output of every data log instruction. The complete table is in the S7-1200 system manual. The codes below are the most common field failures, with root cause and remediation.
| STATUS (hex) | Meaning | Typical Cause | Remediation |
|---|---|---|---|
| 0x0000 | No error | Normal completion | None required. |
| 0x8001 | Data log with the same name already exists | DataLogCreate called twice or after a warm restart | Guard the create call with a one-shot flag. Use DataLogOpen for the second call. |
| 0x8002 | Data log is open and cannot be created | Race condition between create and write | Wait for DONE on create before opening or writing. |
| 0x8010 | Access error (file system fault) | SMC not inserted, not formatted, or write-protected | Insert the SMC, confirm FAT32 format, slide the write-protect tab to unlocked. |
| 0x8011 | Data log name not specified | Empty NAME string | Pass a non-empty name; observe the 22-character NAME limit on older firmware. |
| 0x8012 | Maximum record count exceeded | Data log reached 65,534 records | Implement DataLogNewFile rotation before the limit. |
| 0x8013 | Header string invalid | Header longer than 1,024 bytes or contains illegal characters | Shorten the header; use only ASCII printable characters and the configured delimiter. |
| 0x8014 | Data record type not supported | STRUCT contains ARRAY, nested STRUCT, or STRING elements | Flatten the record to elementary scalar types only. |
| 0x8015 | Maximum number of data logs exceeded | 8 data logs already allocated on the CPU | Delete unused data logs with DataLogDelete; consolidate columns into fewer data logs. |
| 0x8016 | No memory card detected | SMC removed or unseated | Insert SMC; check the diagnostic buffer for IO fault. |
| 0x8017 | Header error | Header delimiter does not match the data record delimiter | Use the same delimiter (semicolon) in header and data. |
| 0x8018 | Data record too large | Record exceeds 512 bytes total | Reduce the number of columns or split into multiple data logs. |
| 0x8019 | Data log not open | DataLogWrite called before DataLogOpen DONE | Sequence the calls; check the instance DB for the open state. |
| 0x801A | Data log ID invalid | ID variable was reset or never assigned | Capture the ID output of DataLogCreate into a retentive tag. |
| 0x801B | Data log write failed | Internal flash or SMC write fault | Check diagnostic buffer; replace SMC if write-endurance is exhausted. |
Beyond the status codes, the most common field failures are:
- File does not appear in the web server: the web server is not activated, or the data log has not been created yet. Confirm the create call returned DONE, then refresh the web page with a hard reload (Ctrl+F5).
- CSV opens with all data in column A: the workstation locale expects comma but the file uses semicolon. Re-import with the correct delimiter, or set the Windows regional list separator to semicolon.
- CPU goes to STOP after a few hours: the user program is overflowing because REQ is never reset. Add the DONE/ERROR edge-reset logic to the write block.
- Timestamp column shows ######: the column is too narrow. Double-click the column border in Excel to auto-fit, or right-click and set column width to 24.
Performance, Scan-Time, and Sizing Considerations
DataLogWrite is a relatively expensive call. The CPU must serialize the record, append it to the file, and update the file index. Typical execution time on a CPU 1214C is 2 to 4 ms per write; on a CPU 1217C it drops to 0.5 to 1 ms. The S7-1200 G2 (firmware V4.5 and later) further reduces this to 0.2 to 0.4 ms. Place the data log write in a cyclic interrupt OB (OB30..OB38) configured for a period longer than the worst-case write time, to avoid interrupt overflow.
Buffering a write to the SMC takes additional time compared to internal flash. The CPU's file system write completes faster than the underlying media, because the S7-1200 maintains a write buffer in RAM. A power loss before the buffer flushes loses the most recent record. For applications where no record may be lost, downgrade the sample rate so each write completes within the buffer flush window, or use the S7-1500 with its buffered write path.
Scan-time impact on the main OB1 is negligible as long as the write call is in a cyclic interrupt. Avoid polling the data log instance DB from OB1; the DONE and ERROR bits are edge-sensitive and should be handled in the same OB that issues REQ.
Data Log vs Trace vs Recipe: When to Use Each
The S7-1200 offers three historical-data mechanisms. Pick the right one for the application.
| Mechanism | Output Format | Best For | Sample Rate | Retrieval |
|---|---|---|---|---|
| Data Log | CSV (text) | Long-term trending, regulatory retention, Excel import | Cycles or events (no hard minimum) | Web server or TIA Portal file browser |
| Trace | Binary (TIA Portal proprietary) | High-speed commissioning traces, control-loop tuning | Down to 1 ms on the CPU 1217 with firmware V4.4 | TIA Portal online trace viewer only |
| Recipe | Binary (TIA Portal proprietary) | Setpoint storage and download to the controller | N/A (read/write by name) | TIA Portal or web server; intended for write-back, not trend. |
Use the data log when the output must leave the controller as a CSV. Use the trace when the diagnostic window is short (seconds to minutes) and the goal is control-loop tuning, because the trace is captured at a much higher rate and visualized with a TIA Portal scope view. Use the recipe when the goal is to store and recall named setpoint bundles, not to record a time series.
Security and Operational Notes
The data log CSV is plain text and contains whatever process values the user program writes into it. Do not log credentials, license keys, or personally identifiable information. If a column contains a tag name that reveals proprietary process information, rename the column header in the HEADER parameter to a generic label such as "Var1" before deployment.
The web server's user database is local to the CPU. Passwords are stored in hashed form on the SMC. Loss of the SMC with default credentials still requires physical access to the controller to extract the hash. Apply a defense-in-depth posture: private network, firewall, and strong passwords. If HTTPS is available on the firmware, enable it to prevent credential interception.
Set the CPU's time-of-day clock accurately using NTP (firmware V4.0 and later supports SNTP client) or a manual set from the HMI. The data log timestamps inherit from the CPU clock; an unsynchronized clock produces data log records that cannot be correlated with other plant data.
Frequently Asked Questions
Does every S7-1200 CPU support data logging?
Yes. The data log function is available on every S7-1200 CPU from the CPU 1211C to the CPU 1217C, including the second-generation S7-1200 G2 models. Firmware V2.0 introduced the core instructions; firmware V4.0 added DataLogClear; firmware V4.4 and V4.5 expanded column and record limits.
Can I retrieve the data log CSV without the web server?
Yes. TIA Portal's online > File browser view lists the data log files on the CPU and SMC, and supports download through the same PROFINET interface used for programming. The web server is the easier path for laptops, but the TIA Portal route works in secure environments where the web server is disabled.
What is the maximum data log file size on the S7-1200?
Each data log file is capped at 65,534 records (a 16-bit counter) regardless of the storage medium. Use DataLogNewFile to rotate to a new file before the limit. On internal flash, the practical limit is lower because of the small available memory; on the SMC, the limit is 65,534 records per file plus the available SMC capacity.
Why does my CSV open in Excel with all data in column A?
The S7-1200 uses semicolon as the field delimiter. Windows systems in the US and UK expect comma. Re-import the file using Data > Text to Columns with semicolon as the delimiter, or change the Windows regional list separator to semicolon for the workstation.
Can I log an array or a string into a data log record?
No. The data log record must be a STRUCT of elementary scalar types only: BOOL, INT, DINT, REAL, WORD, DWORD, BYTE, CHAR, STRING, DTL, TIME, DATE, or TIME_OF_DAY. Flatten any complex types into scalars before passing the structure to DataLogWrite.
How do I avoid losing records on a power cycle?
Use a SIMATIC Memory Card for the data log storage target. The S7-1200 buffers the most recent write to the SMC, preserving it through a power loss. Internal flash is not recommended for any record that must survive a power cycle, because the flush window is shorter and the endurance is lower.