Building a SCADA Totalizer That Survives Counter Rollover and Meter Resets
Computing usage across a wrapping counter without inventing phantom flow: the IEC 61131-3 widths, one mod that covers signed and unsigned, IEEE 1815 IIN1.7 and Freeze and Clear, and an OPC UA Part 4 quality gate.
The daily report says the raw-water meter pushed −4,294,967 gallons overnight. Nothing ran backward. This meter is scaled at 0.001 gallons per pulse, and its pulse count wrapped from the top of a 32-bit register at 4,294,967,295 to zero. The totalizer did new - old as written and produced the counter's whole range — 4,294,967,296 counts, or 4,294,967.296 gallons — with a minus sign in front of it.
A count that went down is one of three things: a rollover, a reset, or a previous value you cannot trust. The totalizer has to treat them differently. If the restart flag is set it is a reset and the increment is just new; if it is not set and the increment is inside what the meter could physically produce, it is a rollover and the increment is (new − old) mod range; if it exceeds that, the interval cannot be accumulated and should be flagged and dropped. The two facts that branch needs are the two the raw tag never carries: how wide the counter is, and whether the device restarted.
Most of the SCADA data that ends up in a report comes from counters like this: flow meter pulse counts, energy kWh accumulators, run-hour meters, product counts off a packaging line. The device holds a number that only ever climbs, and you read usage as the difference between two samples. That works right up until the count hits the top of its range and rolls back to zero — and then every total downstream is wrong until somebody notices the shape of it.
Know the register width
A counter wraps at the top of its data type. You cannot compute rollover without knowing that ceiling. IEC 61131-3 names the widths, and PLC-side datasheets and tag types usually speak in those names.
| Width | IEC 61131-3 type | Max value | Range |
|---|---|---|---|
| 16-bit unsigned | UINT | 65,535 | 65,536 |
| 32-bit unsigned | UDINT | 4,294,967,295 | 4,294,967,296 |
| 32-bit signed | DINT | 2,147,483,647 | 4,294,967,296 (climbing again from −2,147,483,648) |
| 64-bit unsigned | ULINT | 18,446,744,073,709,551,615 | not reached in practice |
IEC 61131-3 defines the ranges of these types; it does not tell you whether a value past the range wraps or sticks at the top. Read the width off the datasheet and confirm the behaviour at the overflow on the bench.
What the width really decides is when this bites. At 1,000 pulses per second, a 16-bit counter wraps every 65,536 ÷ 1,000 = 65.5 seconds. A 32-bit counter on the same input wraps every 4,294,967,296 ÷ 1,000 = 49.7 days. Drop the input to 10 pulses per second and it is 109 minutes for 16-bit and 13.6 years for 32-bit. The difference between 16-bit and 32-bit is not "often" versus "rarely" — it is a one-minute problem versus a plant-lifetime problem.
Two traps here:
- The data model in the MODBUS Application Protocol Specification V1.1b3 has nothing but 16-bit registers. There is no 32-bit integer type in the spec, so a 32-bit counter is a vendor convention pairing two registers, and the order of those two words is not something the spec fixes. Get the order wrong and you get garbage — and it can look like a rollover every time the low word wraps. Confirm the byte and word order before you trust the value. Section 6.3 of the same spec caps one FC3 read at 125 registers, which is 62 32-bit counters per request.
- Some devices hold a 32-bit counter internally but only publish the low 16 bits. You then see rollover at 65,536 even though the datasheet says 32-bit. Trust the wire, not the brochure.
Computing a delta across a wrap
The whole job of totalizer logic is to turn a wrapping raw count into a monotonic usage figure. The common implementation computes new - old and adds the range back when the result is negative, but one modular operation replaces that guard and covers signed counters at the same time. (new - old) mod range returns the same 1 whether a UDINT went from 4,294,967,295 to 0 or a DINT went from 2,147,483,647 to −2,147,483,648.
There is a second signal available to the branch, and it is physics. Multiply the meter's maximum count rate by the elapsed time and you have an upper bound on the increment this interval could possibly hold. A corrected increment above that bound is not a wrap — it is a reset or a garbage read. The code below does both. Change the width and the max rate and it is yours; I ran it before publishing and the assertions pass.
RANGE = 1 << 32 # UDINT. Use 1 << 16 for UINT
MAX_RATE = 1000 # counts per second the meter can physically produce
def delta(old, new, dt, restarted=False):
"""Counts between two good-quality samples dt seconds apart. None = not accumulable."""
if restarted:
return new # reset: the device counted up from zero
if dt * MAX_RATE >= RANGE:
return None # poll too slow: a second wrap cannot be ruled out
d = (new - old) % RANGE # one modular step covers unsigned and signed
return d if d <= dt * MAX_RATE else None # bigger than physics allows -> not a wrap
assert delta(4294967290, 5, 10) == 11 # clean 32-bit wrap
assert delta(2147483647, -2147483648, 10) == 1 # signed wrap, same arithmetic
assert delta(1000, 2000, 10) == 1000 # ordinary interval
assert delta(2000000000, 3, 10, restarted=True) == 3 # reset
assert delta(2000000000, 3, 10) is None # mid-range drop to zero: not physics
assert delta(10, 20, 4294968) is None # 49.7-day gap: unaccumulable
print("ok")
Keep this correction in the calculated-tag expression or edge logic that produces the usage tag, not scattered across every report that reads it. One place, one rule.
The dt * MAX_RATE >= RANGE guard makes an assumption explicit that is usually left implicit: the counter wrapped at most once between the two reads. Poll a 16-bit counter at 1,000 pulses per second on a 60-second interval and you are 5.5 seconds short of its 65.5-second wrap period. Miss one poll there and a full range of counts disappears quietly. The answer in that case is not a cleverer correction — it is reading more often.
Rollover versus reset
Rollover and reset look identical in the numbers, and guessing wrong in either direction is a real error: treat a reset as a rollover and you inject a full range of phantom usage; treat a rollover as a reset and you lose a range of real usage. So sort them with a signal from the device, not with the numbers.
DNP3 hands you that signal outright. IIN1.7 in the IEEE 1815 Internal Indications is Device Restart, and the master clears it by writing a zero to the Internal Indications object — Object Group 80, Variation 1, index 7. The bit stays set until something clears it, so you get to handle one reset on the first poll after a restart and then clear the bit. Many PLCs give you a first-scan or power-up bit doing the same job. If that bit is not wired into the totalizer, every reset will look like a rollover forever.
The better route is not to compute new - old at all. Freeze and Clear in IEEE 1815 — function code 9, or 10 for the no-response form — tells the outstation to copy the counter into a Frozen Counter (Object Group 21) and zero the running counter. The value the master reads afterwards is the interval increment, and neither the width nor the wrap enters the calculation. Prefer this when the device supports it. That is not a taste preference: deleting the code that handles wraparound always beats writing code that handles wraparound correctly.
There is a DNP3-side trap too. Among the Counter variations in Object Group 20, v1 and v5 are 32-bit but v2 and v6 are 16-bit. The variation the master requests decides the width you see, so request a 16-bit variation while believing you have a 32-bit counter and you will watch it wrap at 65,536. The width does not live only in the device datasheet — it lives in the master's configuration as well.
When you have to sort it on the numbers alone, two patterns hold. If old was near the top of the range and new is near the bottom, that fits a rollover. If old was in the middle of the range and new is near zero, it is almost certainly a reset, not a wrap. When it is ambiguous, favour dropping the interval and flagging it for review over inventing a huge number.
Handling bad quality and gaps
Rollover logic assumes you have a trustworthy previous value. Communication gaps break that assumption. If the link was down and you missed several reads, you do not know how many times the counter wrapped in between, so a delta across the gap is a guess.
Where you put the quality gate matters. The StatusCode in OPC UA Part 4 carries severity in its two most significant bits: 00 is Good, 01 is Uncertain, 10 is Bad. Accumulate only when both samples are Good, and gate on those two bits rather than on a list of codes you happened to think of.
A visible failure like Bad_NoCommunication is easy to filter. Uncertain is what slips through. Uncertain_LastUsableValue returns the last value it had in the value field, so logic that only rejects Bad feeds an unchanged previous value into the delta and accumulates zero. That is the path to a report showing flat usage for the whole window the link was dead.
The rest of the handling is short:
- Only compute a delta between two good-quality consecutive samples. If either one is not Good, do not accumulate that interval; mark it and move on. Carrying a delta across a bad-quality gap is how phantom usage gets into a total.
- Hold the last good raw count and its timestamp. When good data returns, decide from
dt × max ratewhether a single delta is defensible. The secondreturn Noneabove is that decision. - Never let the totalizer go negative. A monotonic total that decreases is a signal something upstream is wrong, and it should be caught, not published.
Where to put the totalizer
You have a choice about where accumulation lives, and it drives how robust the total is:
- In the field device / PLC: the device keeps its own accumulated total in a wide register. This is the strongest option because the count never leaves the device as a fragile delta. Read the accumulated engineering-units total directly and let the historian trend it. Prefer this when the device offers it. DNP3's Freeze and Clear belongs in the same category.
- In the SCADA / edge layer: you read the raw wrapping count and compute the running total yourself. This is where all the rollover, reset, and gap handling above has to live. Necessary when the device only exposes a raw counter.
- In the historian as a calculated tag: this is where it goes wrong most often. The Delta aggregate defined in OPC UA Part 13 is the ending value of the interval minus the beginning value, and it has no concept of a counter ceiling — over an interval containing a wrap it returns the negative as-is. Do not point a historian's off-the-shelf delta function at a wrapping raw counter; point it at the corrected usage tag, and validate it the way you would any calculated tag.
Wherever it lives, there should be exactly one authoritative total. Two independent accumulators reading the same counter will drift apart the first time one of them handles a wrap or a gap differently, and then nobody can say which number is right.
Commissioning checklist
- Record the width (UINT / UDINT / DINT / ULINT), the units, and the engineering-units-per-pulse scale for every counter tag, next to the point map.
- Confirm word order for Modbus 32-bit counters. The spec does not fix it, so you need the vendor document and the live value.
- Confirm whether the raw value is the full-width counter or a truncated low word. On DNP3, also check whether the master requests v1/v5 (32-bit) or v2/v6 (16-bit).
- Put rollover correction in exactly one place, keyed to the correct range for that width.
- Compute
range ÷ max count rateand compare it to the poll interval — 65.5 s for a 16-bit counter at 1,000 pulses per second. If the margin is under 2×, shorten the interval. - Wire the restart signal into the totalizer: IIN1.7 on DNP3, a first-scan or power-up bit on a PLC.
- Gate accumulation on StatusCode severity Good, and check that Uncertain is not being counted as Good.
- Assert the running total is monotonic and never negative; alarm if it is not.
- Check that a historian's built-in Delta function points at the corrected usage tag and not at the raw counter.
- Reset the meter deliberately and confirm the total does not jump by a full range.
If you force one test before you leave site, force the wrap. Preset the counter just below its ceiling — on the real device if it lets you, or with a Modbus simulator writing the register if it doesn't — let it roll over, and watch the total step up smoothly with no dip. Everything else about a totalizer you can argue through on paper. The wrap you have to see happen once.