S7-1200 Data Logging: Save Real Values to DB in TIA Portal V13

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

S7-1200 Data Logging: Save Real Values to DB in TIA Portal V13

Capturing a process variable once per hour and moving it to a historian or report is a routine task that nearly every S7-1200 application eventually needs. TIA Portal V13 (with V13 SP1/SP2) supports several mechanisms for this on the S7-1200 family, but the native DataLog instruction set is reserved for the S7-1500 generation. The S7-1200 must use a combination of data blocks, time-of-day interrupts, the SIMATIC memory card, and either the integrated Web server or FTP server to move data out of the controller. This article walks through the complete architecture, hardware selection, programming patterns, and operator workflow required to log a single REAL value every hour, save the day's batch to the memory card, transfer it to a PC running WinCC Flexible RT 2008 SP5, and then reset the buffer pointer for the next day.

1. Use-Case Definition and Architecture Overview

The target application has the following requirements, which match the original field request:

  • Read a process REAL value (e.g., a flow, temperature, or pressure scaled value).
  • Sample the value once per hour, 24 samples per day, using a time-of-day interrupt (TOD).
  • Store the 24 samples in a data block (DB) on the CPU's load memory (the SIMATIC memory card).
  • Allow an operator to connect to the S7-1200 from a PC and pull the day's file.
  • Display the file content in a WinCC Flexible RT 2008 SP5 runtime on the same PC.
  • After successful upload, set a confirmation bit that resets the DB pointer to slot 0.

The reference architecture looks like this:

Process Sensor (Analog Input) S7-1200 CPU TOD OB + Sample FB DB "LogData" (24 x REAL) in load memory SIMATIC Memory Card /LOG/2024-01-15.csv Web / FTP Server on PN interface PC + WinCC Flex RT pulls CSV, resets bit

2. Hardware Selection

Any S7-1200 CPU with PROFINET can be used, but specific firmware thresholds gate the features used in this guide. The matrix below shows the relevant minimum firmware versions.

CPU Order Number (MLFB) Min. Firmware for Web/FTP Min. Firmware for File Operations Notes
CPU 1211C DC/DC/DC 6ES7211-1AE40-0XB0 V4.0 V4.2 No SD card slot, internal only
CPU 1212C DC/DC/DC 6ES7212-1AE40-0XB0 V4.0 V4.2 SD card slot present
CPU 1214C DC/DC/DC 6ES7214-1AG40-0XB0 V4.0 V4.2 Common in field retrofit jobs
CPU 1215C DC/DC/DC 6ES7215-1AG40-0XB0 V4.0 V4.2 2 PN ports, recommended
CPU 1217C DC/DC/DC 6ES7217-1AG40-0XB0 V4.0 V4.2 High-performance option

For this design, the CPU 1215C (6ES7215-1AG40-0XB0) with firmware V4.2 is the recommended target because it has dual PROFINET ports (allows separation of the operator network from the field network) and supports all file system instructions. A SMC (SIMATIC Memory Card) of 4 MB (6ES7954-8LC03-0AA0) or larger is required for non-volatile file storage.

Note: The DataLogCreate, DataLogOpen, DataLogWrite, and related instructions documented in the S7-1200 System Manual are not available in TIA Portal V13 for the S7-1200; they are part of the S7-1500 system library. The S7-1200 must implement its own file write using FileWriteC / FileWrite / FileOpen from the "Standard > File system" library, available in V13 SP1 onward.

3. Prerequisites

  • TIA Portal V13 SP1 (6AV2101-0AA03-0AA7) or V13 SP2 (6AV2101-0AA03-0AA8) installed on the engineering PC. V13 SP1 is the minimum that supports the file system instructions in their current form.
  • STEP 7 Basic V13 license (or STEP 7 Professional V13 if the project will scale to S7-1500).
  • WinCC Flexible 2008 SP5 (6AV6613-0AA01-1CA5) with WinCC Flexible RT 2008 SP5 runtime license (6AV6613-1AA01-1CA5) installed on the operator PC.
  • S7-1200 CPU 1215C FW V4.2 or higher. Lower firmware will compile but will fault on FileOpen.
  • SIMATIC Memory Card inserted and formatted by the CPU (this happens automatically the first time the card is inserted and the CPU is powered).
  • Network connectivity between the engineering PC, the S7-1200 PROFINET interface, and the operator PC. Static IP addresses assigned; the S7-1200 default is 192.168.0.1.

4. TIA Portal V13 Project Setup

  1. Open TIA Portal V13 and choose Create new project. Name the project HourlyLog_S71200.
  2. Add a new device: Add new device > Controllers > SIMATIC S7-1200 > CPU > CPU 1215C DC/DC/DC > 6ES7215-1AG40-0XB0.
  3. Open Device configuration > Properties > General > PROFINET interface [X1] and assign the IP address 192.168.0.1 with subnet mask 255.255.255.0.
  4. Add the Time of day interrupt OB by double-clicking Program blocks > Add new block > Organization block > Time of day interrupt. Name it OB_Hourly.
  5. In OB_Hourly > Properties > General > Time of day, set the start time (e.g., 01.01.2015 00:00:00) and the period to 1h (3,600,000 ms).

The hourly OB is the trigger that the application will use to call the sample-and-store logic. Time-of-day interrupts in the S7-1200 are accurate to within 1 second per day as long as the CPU time is synchronized. For higher accuracy, enable NTP time synchronization on the PROFINET port.

5. Designing the Logging Data Block

Create a new global DB named DB_LogData. Disable the Optimized block access option (TIA Portal V13 SP1: uncheck Optimized block access in the DB properties); the file system instructions require the standard access mode for byte-offset addressing.

The DB structure is intentionally simple because the application is a single REAL stream plus metadata.

Address Name Type Initial Value Comment
DBW0 SampleCount INT 0 Samples written today (0..24)
DBW2 DayKey INT 0 Julian day of last write
DBD4 SampleTimestamp DTL DTL#1970-01-01-00:00:00 Time of the most recent sample
DBD12 Samples[0] REAL 0.0 Midnight sample
DBD16 Samples[1] REAL 0.0 01:00 sample
... ... REAL 0.0 ...
DBD104 Samples[23] REAL 0.0 23:00 sample
DBX108.0 UploadDone BOOL FALSE Operator ack of upload

The total size of the DB is 109 bytes. All slots are retain (set Retain check box in the DB properties) so the buffer survives a warm restart of the CPU.

Watch out: In TIA Portal V13, the maximum size of a single data block on the S7-1200 is 64 KB. The 109-byte footprint here is comfortable. If you need a 10-minute sample (144 samples/day), allocate 1.2 KB; if you need 1-minute samples, you will need a separate DB per day or use the file system directly (recommended).

6. FB SampleAndStore – Circular Buffer in STL / SCL

Create a new function block FB_SampleAndStore with the following interface:

FUNCTION_BLOCK FB_SampleAndStore
VAR_INPUT
    i_ProcessValue : REAL;        // scaled process value
    i_DayKey       : INT;         // current day-of-year
    i_Rst          : BOOL;        // operator confirms upload; reset pointer
END_VAR
VAR_OUTPUT
    o_SampleCount  : INT;         // how many slots filled today
    o_DayActive    : BOOL;        // TRUE while current day is in progress
END_VAR
VAR
    s_SlotIdx : INT;              // internal pointer 0..23
END_VAR

Implementation in SCL (preferred for readability):

// Detect day rollover or operator reset
IF (i_Rst = TRUE) OR (i_DayKey <> "DB_LogData".DayKey) THEN
    "DB_LogData".SampleCount := 0;
    "DB_LogData".DayKey      := i_DayKey;
    s_SlotIdx                 := 0;
END_IF;

// Write sample at the next free slot
IF s_SlotIdx < 24 THEN
    "DB_LogData".Samples[s_SlotIdx] := i_ProcessValue;
    s_SlotIdx                       := s_SlotIdx + 1;
    "DB_LogData".SampleCount        := s_SlotIdx;
END_IF;

// Update the timestamp from CPU clock
"DB_LogData".SampleTimestamp := DTL#1970-01-01-00:00:00;
RT_INFO(Timestamp := "DB_LogData".SampleTimestamp);

o_SampleCount := "DB_LogData".SampleCount;
o_DayActive   := (s_SlotIdx < 24);

The RT_INFO instruction is part of the TIA Portal V13 system library and reads the local CPU clock. It is available on the S7-1200 from firmware V4.0 onward.

7. OB_Hourly and Main OB Wiring

Inside OB_Hourly add the following SCL code. The OB runs once per hour; the operator reset is read from DB_LogData.UploadDone which is set by the operator panel in WinCC Flexible RT.

// Compute the day-of-year (1..366) for the buffer key
#iDayKey := (DT_DATE_YEAR(RT_INFO(TIMESTAMP)) * 1000) + RT_INFO(DAY_OF_YEAR);

// Reset request is a 1-second pulse from the operator
IF "DB_LogData".UploadDone = TRUE THEN
    "DB_Inst_Sample".i_Rst := TRUE;
    "DB_LogData".UploadDone := FALSE;          // clear the request
ELSE
    "DB_Inst_Sample".i_Rst := FALSE;
END_IF;

// Pass the current process value (here from IW64 of an SM1231)
"DB_Inst_Sample".i_ProcessValue := "IW64_AI_Flow" / 1000.0;
"DB_Inst_Sample".i_DayKey       := #iDayKey;
"DB_Inst_Sample"();                         // call the FB

Drop a single-instance DB DB_Inst_Sample for the FB so the retain variables are kept across CPU restart. Also place the call in OB1 as an unconditional call with i_Rst := FALSE so the buffer pointer is initialised on the first scan.

8. File System Export to the SIMATIC Memory Card

To make the data available to the operator PC, the buffer must be written to a file on the memory card. The S7-1200 supports a FAT16 file system on the SMC, and exposes instructions FileOpen, FileWriteC, FileClose, FileRead from the standard library. Below is an export FB that writes a CSV file under /LOG/<date>.csv.

FUNCTION_BLOCK FB_ExportCsv
VAR_INPUT
    i_Trigger       : BOOL;       // rising edge triggers one file write
END_VAR
VAR
    s_FileName      : STRING[40];
    s_Header        : STRING[80];
    s_Line          : STRING[80];
    s_hFile         : DWORD;      // file handle
    s_RC            : WORD;       // return code
    i_Idx           : INT;
    rt              : DTL;
END_VAR
// Build a date-stamped file name like /LOG/20240115.CSV
RT_INFO(Timestamp := rt);
s_FileName := CONCAT(IN1 := '/LOG/', IN2 := DTL_TO_STRING(rt));
s_FileName := LEFT(IN := s_FileName, LEN := 18);  // strip the time portion
s_FileName := CONCAT(IN1 := s_FileName, IN2 := '.CSV');

// Open the file (write, create if not present)
s_hFile := FileOpen(FileName := s_FileName,
                    Mode     := 'w+',
                    Encoding := 1);  // 1 = ASCII / UTF-8 in V13 SP1

IF s_hFile <> 0 THEN
    s_Header := 'Index,TimeStamp,Value\r\n';
    FileWriteC(hFile := s_hFile, Format := '%s', Value := s_Header);

    FOR i_Idx := 0 TO 23 DO
        s_Line := CONCAT(IN1 := INT_TO_STRING(i_Idx), IN2 := ',');
        s_Line := CONCAT(IN1 := s_Line, IN2 := DT_TO_STRING(FILETIME_FROM_DTL(rt)));
        s_Line := CONCAT(IN1 := s_Line, IN2 := ',');
        s_Line := CONCAT(IN1 := s_Line, IN2 := REAL_TO_STRING("DB_LogData".Samples[i_Idx]));
        s_Line := CONCAT(IN1 := s_Line, IN2 := '\r\n');
        FileWriteC(hFile := s_hFile, Format := '%s', Value := s_Line);
    END_FOR;

    FileClose(hFile := s_hFile);
END_IF;

Call this FB from OB1 with i_Trigger := "DB_LogData".UploadDone rising edge. After a successful write, set DB_LogData.UploadDone := FALSE in the same cycle.

Error code checklist for FileOpen / FileWriteC on S7-1200 FW V4.2:
  • 0001 – No memory card inserted.
  • 0002 – File system not formatted (re-format the SMC with the CPU control panel in TIA Portal: Online & diagnostics > Functions > Format memory card).
  • 0003 – File not found (applies to FileRead).
  • 0004 – Access denied (file already open in exclusive mode).
  • 0007 – Path or file name invalid (avoid spaces, special characters, > 31 char name on FAT16).

9. Web Server and FTP Server Activation

Two transfer methods are available on the S7-1200 PROFINET port: HTTP/Web server (download the file as user-defined page or as raw file via the Files page) and FTP server (any FTP client can GET the CSV). The Web server is configured in Device configuration > Web server:

  1. Activate the Web server globally.
  2. Enable User-defined Web pages only if you intend to add a custom HTML wrapper (not required for raw file download).
  3. Add an administrator user (e.g., op with password) and grant Read files privilege.
  4. Add the standard S7-1200 Web page to the project; this exposes the Files tab from which an operator can browse /LOG and download the CSV.

For FTP, navigate to Device configuration > PROFINET interface > Properties > FTP server (available from V13 SP1 Update 4 onward). Enable the FTP server and set the same user credentials. The default FTP root is the memory card root, and the user sees the directory tree exposed.

Method URL / Command Authentication Operator PC Tool
Web server (Files tab) http://192.168.0.1/Portal/Portal.mwsml?PriNav=Fils User + password Browser
Web server (raw file) http://192.168.0.1/LOG/20240115.CSV User + password Browser / WinCC
FTP ftp://192.168.0.1/LOG/20240115.CSV User + password Windows Explorer, FileZilla

10. WinCC Flexible RT 2008 SP5 Operator Panel

On the operator PC, open WinCC Flexible 2008 SP5, open the project, and add a screen DailyLog. Add the following IO fields and buttons:

  1. An IO field showing DB_LogData.SampleCount (HMI tag, address DB1, DBW0, update cycle 1 s).
  2. An IO field showing DB_LogData.DayKey for cross-check.
  3. A button labelled Upload today's file. The button's Click event uses a Set bit function targeting DB_LogData.UploadDone. After the CSV is produced, the S7-1200 clears this bit. The button should be grayed while the bit is set (animation on visibility).
  4. A button labelled Acknowledge upload & reset that sets a separate HMI_to_PLC.Ack bit; the PLC uses this to clamp the reset condition.
  5. A view displaying the last downloaded file path. Use a Browser control (Internet Explorer ActiveX in WinCC Flexible) to point to ftp://op:[email protected]/LOG/ for a browsable list of files, or add a Recipe view bound to the FTP path so the operator can pull the day's CSV into the runtime.

Configure the connection in WinCC Flexible as S7-1200 / S7-1500 with the CPU's PROFINET IP and the slot-1 rack. The connection uses ISO-on-TCP (port 102) and is set up by TIA Portal automatically when the project is downloaded.

11. Operator Workflow (End-to-End)

  1. Throughout the day, OB_Hourly fires once per hour, calls FB_SampleAndStore, and writes the REAL value into the next slot of DB_LogData.Samples.
  2. At the end of the shift, the operator opens WinCC Flexible RT and clicks Upload today's file. The button sets DB_LogData.UploadDone := TRUE for one cycle, which triggers FB_ExportCsv to write /LOG/YYYYMMDD.CSV to the SMC.
  3. The operator opens the Web server's Files tab (or an FTP client) and downloads the CSV to a local path on the PC (e.g., C:\Reports\20240115.CSV).
  4. WinCC Flexible RT displays the CSV via a Recipe view or the Browser control. The operator generates the report (PDF export) and prints it.
  5. The operator clicks Acknowledge upload & reset. The PLC clears the slot pointer (via i_Rst = TRUE in the next hourly cycle) and the next sample will be written to Samples[0] again.

12. Verification and Commissioning Checklist

Step What to Check Pass Criterion
Compile & download TIA Portal > Online > Compile and download blocks No compile errors, CPU in RUN
Time-of-day OB Watch the call count of OB_Hourly from Online & diagnostics > Cycle / time Increments by 1 every hour
Buffer fill Monitor DB_LogData.SampleCount online Increments 1 per hour from 0 to 24
File write Trigger export, browse to /LOG on the SMC via the Web server File exists with 25 lines (header + 24)
Web/FTP access From operator PC, http://192.168.0.1/Portal/Portal.mwsml with credentials Files tab lists the CSV
WinCC RT refresh Open RT, click upload, observe the file appears under the configured path CSV opens, values match the DB
Reset behaviour Click Acknowledge; observe SampleCount going to 0 at the next hour tick Pointer back to 0, no overwrite of unsent data

13. Performance, Sizing and Power-Loss Considerations

  • The 109-byte DB fits well within the 16 KB default data block limit of the S7-1200 and is retain, so it survives power loss with the SMC present.
  • If the buffer must be larger (for example, 10-minute samples, 144/day, holding a week = 1008 samples), prefer writing directly to a CSV file on the SMC rather than expanding DB_LogData. The file system instructions were specifically added to S7-1200 FW V4.2 to remove this design pressure.
  • At power loss, the S7-1200 writes the retain area to the SMC automatically. A warm restart restores the data; a cold restart (memory reset) wipes it. Document this in the operator manual.
  • Sample FileOpen is blocking up to 500 ms. Place the call in a low-priority OB (such as OB_Hourly or a dedicated OB200 cyclic interrupt at 1000 ms) to avoid starving OB1.

14. Troubleshooting Matrix

Symptom Likely Cause Fix
SampleCount does not increment Time-of-day OB not started or period wrong Re-download the OB; in Online & diagnostics, verify the next trigger time and the OB start config bit.
Values all read 0.0 Analog input scaling incorrect (e.g., IW64 / 1000.0 against a 4..20 mA signal) Check the SM1231 configuration in Device configuration > AI and the scaling constant.
FileOpen returns 0 No SMC inserted, or SMC not formatted Insert SMC and cycle power; the CPU will format it. Reinsert in the engineering PC and accept the format prompt.
Web server returns 404 for /LOG/... Web server not enabled or user lacks Read files privilege Enable the Web server and grant the privilege to the user account.
FTP access denied FTP server not activated, or wrong user Activate FTP on the PROFINET interface and re-enter the password in the operator PC's credential store.
Buffer rolls over before operator retrieves 24-slot ring not reset after day rollover Add the day-key rollover logic shown in FB_SampleAndStore so a new day starts a new buffer automatically.
WinCC tag shows #### Address not matching the data block layout in TIA Portal Recompile the HMI tags with HMI tag management > Compile; addresses on the HMI side use the same offsets as the DB.

15. FAQ

Can I use the DataLogCreate instruction on the S7-1200 in TIA Portal V13?

No. The DataLog instruction family is supported only on the S7-1500 generation. On the S7-1200 (firmware V4.2 and above), use the FileOpen, FileWriteC, and FileClose instructions from the "Standard > File system" library to write CSV files to the SIMATIC Memory Card.

What is the minimum firmware for the file system instructions on the S7-1200?

FileOpen, FileWriteC, FileRead, and FileClose are supported from S7-1200 firmware V4.2. TIA Portal V13 SP1 Update 2 (or later) is required to see the instructions in the project library.

How do I prevent data loss on a power cycle?

Mark the logging data block as "Retain" in its properties and keep a SIMATIC Memory Card inserted in the CPU. The S7-1200 mirrors retain tags to the SMC so a warm restart restores the last buffer state.

Why is my optimized DB not accepted by FileWriteC?

The file system instructions use absolute byte offsets and expect standard (non-optimized) block access. Open the DB properties in TIA Portal V13 and uncheck "Optimized block access" before downloading.

Can WinCC Flexible RT 2008 SP5 read the CSV directly from the S7-1200?

Yes, using the integrated FTP connection: configure a connection of type "SIMATIC S7-1200/S7-1500" plus the FTP path. Alternatively, the operator downloads the CSV to a local folder and the runtime opens it through a recipe view or a script.

Back to blog