How to detect / prevent counter overflow

I have a counter in a 16-bit field, which increases / decreases for a while using peripheral equipment.
I periodically measure its value to summarize the difference in the 32-bit field.

My problem is detecting an overflow / underflow of a 16 bit field when calculating the difference.

Take an example:
On sample n-1, the value of the Vn-1 counter is 65530.
As a sample n, the value of the counter Vn is 4.
The counter has been increased by 10. But the difference (Vn-Vn-1) will be approximately 65529 (not sure of the exact value).

The only way to detect this overflow is to compare the difference value with a fixed value that exceeds the maximum value (I choose 10000).
Do you know a solution to manage this overflow without comparing with this subjective value?

Here is a sample code:

static sint32 overallCount = 0; sint32 diff; static sint16 previousValue = 0; sint16 currentValue; currentValue = sampleValue(); diff = ((sint32) currentValue) - previousValue; if(diff > 10000) { diff -= 65536; } else if ((-diff) > 10000) { diff += 65536; } overallCount += diff; 
+6
c embedded overflow
source share
4 answers

My previous answer had some errors, so I rewrote it, but the idea is the same, use unsigned types correctly.

Make currentValue and previousValue as unsigned integers of the selected size (e.g. uint16_t). Then just subtract them. Since the difference will be implicitly raised to int , if int is a larger type than uint16_t , you will need to do or implicitly convert the result back to uint16_t . So:

 static uint16_t previousValue; uint16_t currentValue = sampleValue(); uint16_t diff = currentValue - previousValue; 

This uses an implicit conversion in assignment, but you can use it if you want.

+7
source share

Another option is to simply track the overflow account. Using uint16_t for values,

 if (currentValue < previousValue) overflows++; 

Then, to get a 32-bit value, you combine overflows with currentValue.

result = currentValue | (overflows << 16);

+1
source share

Here are some ideas for you:

  • Make an addition to the 32-bit field and make sure that the result fits in the 16-bit field afterwards.
  • Check if the oldest value of the old value has changed as a result of adding.
  • Make an addition to the assembly and then check the carry flag.
0
source share

You can try using the Kalman filter to detect overflow.

0
source share

All Articles