32bit integrator in C

Hello everyone,

I have a question regarding implementing a 32bit integrator in C. I am working on an application where I have a 20bit up/down counter which holds energy being consummated. In the application I need to constantly integrate value of this counter in order to get a total amount of energy that has been consumed. I have implemented something as follows to achieve this but my question is when the roll-over happens how can that be handled.

struct Energy_t {
	uint32_t new;   /* new energy value - 32 bits */
	uint32_t old;    /* previous energy value - 32 bits */
	uint32_t quant; /* new - old, measure of power - 32 bits */
	int32_t frac;    /* fractional part of energy integrator - 32 bits */
	int32_t integ;   /* integer part of energy integrator - 32 bits */
};

static struct Energy_t Active;


// Extract 20 bit counter value from internal device register
Active.new = (dap >> 8) & 0xFFFFF;
		
// Calculate difference between new and old reading
Active.quant = Active.new - Active.old;

// Update old reading for next calculation
Active.old = Active.new;

// Check if difference is positive
if (Active.quant > 0)
{
        // Add the difference to previous count
	Active.frac += Active.quant;
	
        // Check if threshold is reached
	if (Active.frac >= 0x20000)
	{
                // Increment the integral variable by 1
		Active.integ = (Active.integ + 1) % 0xFFFFFFFF;
                // Change the fractional part to 0 for next integration
		Active.frac = 0;
	}
}

In the above code, when the roll over happens the difference between the old and the new value would be negative how can this situation be handled as to avoid any lapse in accumulation. The measurement is carried out in a task which runs at an interval of 50ms.

Hope someone here can help me in this matter.

Thank you in advance.

Best regards,
Owais.

If, after summation, the result is smaller than before, then rollover has occurred, so you can add one MSB to your result.

Thanks for the response and for moving my question to a more suitable place.

You mean to say that I need to keep a check after summation, but wouldn't that corrupt the fractional part since after the summation the fractional part would already be updated and if it is smaller than before the threshold value would be corrupted.

What if I check the difference between the new and the old value and see if the new value is smaller than old I can maybe do it like this:

if new < old
difference = 0xFFFFF - old;

old = new;

frac += difference;