IMDTouchKnowledge BaseShop main store

How-to

How to calculate daily flow totals and midnight rollover in WinCC

HMI and touchscreens Published 7 min read

Short answer

Yes — no archive query is needed. One C action in the Global Script editor, on a several-second cyclic trigger, keeps today's running total; a time-based trigger at 00:00 rolls it, so yesterday takes today's value and today restarts at zero. Compute each day as a totalizer difference when the meter reads cumulative mass, or as flow × elapsed seconds ÷ 3600 when it reads a rate, and give the calculation one owner: the PLCs, or one designated server.

On this page
  1. Pick the arithmetic before you touch the script
  2. Give the calculation exactly one owner
  3. Build the two actions, step by step
  4. The two script bodies
  5. Worked example: one 4.2 t/h meter on a 5 s cycle
  6. What three months of archive retention gives you
  7. Prove the rollover before you trust it
  8. Questions asked

WinCC gives you both numbers without any query against the archive database, and the concrete fix is this: two C actions in the Global Script editor, one on a cyclic trigger set to 5 s, one on a time-based trigger set to 00:00. The cyclic action keeps today's running total; the time-based action fires at 00:00 to roll the totals — yesterday takes today's value, today restarts at zero. The daily quantity itself is a totalizer difference when the meter reports cumulative mass, or flow × elapsed seconds ÷ 3600 when it reports only a rate — at 4.2 t/h on a 5 s cycle, each execution adds 4.2 × 5 ÷ 3600 = 0.00583 t. Give the calculation exactly one owner, the PLCs or one designated server, so a redundant pair never counts the same material twice.

Pick the arithmetic before you touch the script #

A rate and a totalizer are different quantities. A rate is mass per hour; a totalizer is the mass that has passed since its reference point. Subtracting two rate samples produces a change in flow rate, not the mass transferred during the day — the most common error in this job. Classify every meter tag first, then apply one of two methods:

  • Difference method — the tag is cumulative mass. Record the reading at the day boundary; today equals the current reading minus that snapshot, and yesterday equals the midnight-to-midnight difference. Timing errors cancel, because the same slow clock reads both boundaries.
  • Integral method — the tag is a rate. Each execution adds rate × elapsed seconds ÷ 3600 to today's total.
What the tag does Most likely meaning Deciding check
Rises steadily while material flows Cumulative totalizer Meter scaling and units: tonnes, not tonnes per hour
Swings with process demand Instantaneous rate Compare against the meter's local flow display
Steps down after a meter restart Counter reset or wrap Compare successive raw readings; handle resets explicitly
Totals freeze unless a picture is open Calculation tied to screen activity The trigger belongs in the action's Trigger tab, not a picture event

A tag labeled as a counter but scaled in tonnes per hour is not proof of accumulated mass — read the meter configuration before trusting the label. Decision: whenever a cumulative reading exists, use the difference method and skip integration entirely; integrate only meters that give you nothing but a rate.

Give the calculation exactly one owner #

Your installation is PC supervision — one engineering station and a redundant server pair — not an operator panel, so nothing here depends on a panel task scheduler. That matters for ownership. If both servers run the accumulating action, each builds its own copy of today's total and both write the result tag: increments land twice, or one server overwrites the other's state after every failover.

Two clean architectures:

  • PLC-owned. Each PLC totalizes its own meters and WinCC only reads and displays the results. Totals then survive supervision outages and server restarts. Agree one accounting-day definition and one clock reference across the controllers before combining their numbers. For the controller-side version of the same problem, see resolving a PLC yesterday totalizer reset at midnight.
  • One designated server. The WinCC action runs on a single named server; the standby displays the same tags without executing the calculation, and ownership transfer is written into the failover procedure.

Decision: PLC-owned is the default when the totals feed reporting that must not depend on PC availability; one designated server is acceptable when the failover procedure is documented and tested.

Build the two actions, step by step #

  1. Classify every meter tag as a rate or a cumulative quantity, and record its units, scaling and reset behavior.
  2. Decide the owner as above, and open the owner's project.
  3. In the Global Script editor (C), create a new action for the running total.
  4. Select the action, then open Edit → Information → Trigger (labels are localized on non-English installations). Siemens' scripting documentation defines a cyclic trigger as an interval plus a starting point; set an interval of a few seconds — 5 s is a sound starting point.
  5. Write the cyclic script following the classification from step 1.
  6. Create a second action for the rollover. In the same Trigger tab choose the time-based option and set it to 00:00. The script sets yesterday to today's value, zeroes today, and — under the difference method — snapshots the meter counter as the new day start.
  7. Save both actions in the editor, then reactivate the runtime. An action edited while the project runs can stay inert until it is saved and the runtime restarted.
  8. Verify execution with every picture closed. Global Script actions run in the runtime regardless of what is on screen; a total that only moves when a picture is open means the trigger landed in a picture event instead of the action's Trigger tab.

The 00:00 boundary is only as good as the clock behind it — setting HMI clock time from PC and PLC daily keeps the PCs and the controllers from drifting apart.

The two script bodies #

The names below are illustrative; substitute your own tag dictionary entries, and read and write tags with the documented tag-access functions of the C environment.

Cyclic action, integral method:

double rate_tph  = 0.0;  // flow tag read this cycle, t/h
double elapsed_s  = 0.0;  // measured seconds since the previous execution
double today_t    = 0.0;  // persistent result tag, t

today_t = today_t + rate_tph * elapsed_s / 3600.0;

Cyclic action, difference method — one line, no accumulation:

today_t = counter_t - day_start_t;   // both persistent tags, t

Time-triggered rollover action:

yesterday_t = today_t;    // completed day, t
today_t     = 0.0;        // restart
day_start_t = counter_t;  // difference method only

Measure elapsed_s with the C environment's time functions; assuming the nominal cycle turns every delay into lost mass. And because the cyclic action runs every few seconds for months, keep string work out of it — fixing WinCC C script memory growth from string buffers shows what an unchecked buffer does to a long-running runtime.

Worked example: one 4.2 t/h meter on a 5 s cycle #

Inputs:

  • The meter reports mass flow in t/h — the plant's meters are scaled in tonnes per hour, so the integral method applies.
  • Cyclic trigger of 5 s — the several-second cadence this kind of runtime tolerates; 1 s is possible but heavier.
  • Day boundary at 00:00, executed by the time-based trigger.
  • The readings below are illustrative; the arithmetic is what transfers.

Rule in words: each execution adds the rate times the measured elapsed seconds, divided by 3600, to today's total.

Arithmetic at a constant 4.2 t/h:

4.2 t/h × 5 s ÷ 3600 s/h = 21 ÷ 3600 = 0.00583 t — about 5.8 kg added per cycle.

Result over a full day at that rate: 4.2 t/h × 24 h = 100.8 t, cross-checked as 17,280 cycles (86,400 ÷ 5) × 0.00583 t ≈ 100.8 t. A delayed execution measured at 8 s adds 4.2 × 8 ÷ 3600 = 0.00933 t; assuming 5 s would lose 3.5 kg on that one cycle, which is why elapsed time is measured, never assumed.

Bench check that proves the setup: after 60 s at a constant 4.2 t/h the tag must read 4.2 × 60 ÷ 3600 = 0.070 t. If it does not, the elapsed measurement or the trigger is wrong — fix it before commissioning.

If the same meter also exposes a cumulative reading — 1,486.2 t at one midnight, 1,517.9 t at the next — yesterday is 1,517.9 − 1,486.2 = 31.7 t, independent of any script timing.

Decision: a cumulative reading wins every time, so above zero availability of a counter tag, use the difference and drop the integration. Run PC integration only for meters that give nothing but a rate, and treat those totals as indicative until reconciled against the meter's own counter.

What three months of archive retention gives you #

Retention keeps history; it does not manufacture boundary values. The archive stores samples on its own logging schedule, so a sample taken exactly at 00:00:00 usually does not exist, and silently taking the nearest one changes the interval you measured. If you reconstruct completed days from history, define the boundary rule first and check whether the archived tags are totalizer readings or rate samples — the same difference-versus-integral decision applies.

Access the archive through the documented archive-access and export facilities for the installed WinCC version, not a hand-written query against the runtime database. Decision: the live totals come from the two actions; the archive is for backfill after a failure and for audit.

Prove the rollover before you trust it #

  1. Temporarily set the rollover action's time trigger a few minutes ahead of the current time.
  2. Close every picture and watch one rollover happen — the action must fire with nothing on screen.
  3. Confirm yesterday froze at the last running value and today restarted from zero.
  4. Confirm exactly one machine wrote the result; two writers means the ownership decision was never made.
  5. Restore the trigger to 00:00 and let the first real midnight run unattended before anyone reports from the numbers.

Questions asked

What happens if the owning server is down at midnight?

The time trigger cannot fire while runtime is stopped, so the totals stay on the old day until runtime comes back. Make the rollover self-healing: store the processing date in a tag and let the action roll whenever the stored date differs from the current date. A server restarted at 03:00 then rolls the day once, on its first execution, instead of waiting for the next midnight.

Do I have to read the system clock inside the script?

No. The rollover belongs to the time-based trigger, not to a clock comparison in code; that is the cleanest way to fire at 00:00. For the elapsed time between cyclic executions, call the time functions of the C scripting environment — the function reference is part of Siemens' WinCC scripting documentation. Measure elapsed seconds; never assume the nominal interval.

The meter counter resets after a power cycle. How do I keep the daily difference honest?

Detect the reset when the current cumulative reading is smaller than the previous one, and add the last pre-reset reading to a carry value that the difference uses. If resets are routine, move the totalizing into the PLC, where retained controller memory carries the state through supervision outages.

How often should the cyclic action run?

A 1 s cycle is possible and sometimes used, but a several-second cadence keeps script load low on a busy runtime. Because the script integrates with measured elapsed time, the interval sets resolution, not correctness: a slower cycle approximates a swinging rate more coarsely, but it does not lose time.

Why does my integrated total drift from the meter's own counter?

The script treats each sampled rate as representative of the whole interval, so flow changes between samples are approximated, while the meter totalizes continuously. Small daily differences are therefore expected. When the meter exposes a cumulative reading, use the midnight difference instead — it inherits the meter's own integration, and timing errors cancel at both boundaries.

Keep reading

  • Troubleshooting

    Fixing WinCC C Script Memory Growth From String Buffers

    Yes - writing a database field through a pointer aimed at a string literal is undefined behavior and a buffer overrun into 10 bytes of read-only storage, and it is not the leak. Days of script.exe growth come from database objects acquired per call and never released. Fix both: pass a caller-owned buffer with its capacity, copy at most bufferSize - 1 bytes, terminate explicitly, and release every acquired object on every exit path.

    HMI and touchscreens

  • How-to

    Enforcing HMI Setpoint Deviation Limits Outside the Panel

    Run the deviation check in a Gateway Tag Change script, not a Vision client event, and compare the new value against the recipe value so setpoints cannot creep 100 to 124 in legal steps. Write the corrected value back once; with a recipe comparison the loop ends after one extra event. Move the band check into the PLC for any axis that cannot tolerate the poll-to-writeback window on a bad setpoint.

    HMI and touchscreens

  • Troubleshooting

    Why WinCC Runtime Reports Project Is Locked and How to Recover

    "Project is locked" in WinCC Runtime is an ownership conflict, not a license fault: a live session, or a stale ProjectOpened.lck left behind by a crash or power loss, still claims the project. Close every session that could own it, back it up, then clear the lock with reset_wincc.vbs or by removing ProjectOpened.lck; on a client, open the project by its UNC path.

    HMI and touchscreens