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;
c embedded overflow
greydet
source share