# Average of 10 readings, wrong

I am reading from loadcell and calculating the average of last 10 readings. But when the load cell reads something more than 3800 g the average gets negative, how? The mass I read are not negative numbers. I have been trying to find my mistake but I am not able to. Any help?

#include "HX711.h"

int total = 0;                  // the running total
int average = 0;                // the average
int mass  =0;

HX711 scale;

float a = 0.0088;
float b = 2009.7;

void setup() {
// initialize serial communication with computer:
Serial.begin(9600);
// initialize all the readings to 0:
}
}

void loop() {
// convert to mass

// advance to the next position in the array:

// if we're at the end of the array...
// ...wrap around to the beginning:
}

// calculate the average:
// send it to the computer as ASCII digits

Serial.print("   ");
Serial.print(average);
Serial.println("");
delay(1000);        // delay in between reads for stability
}
else{
}
}
• It's called "integer wraparound" - int can only hold between -32768 and +32767 on an 8-bit Arduino. Commented Jun 2, 2021 at 12:50
• Omg, thank you very much for the help. I was struggling with it Commented Jun 2, 2021 at 12:59
• tip, if you know that it only should contain positive numbers, declare as an unsigned integer. Commented Jun 2, 2021 at 14:53

Another option would be use 'long' as a variable type for total. Depending on your application, you also might look into an exponentially weighted moving average (EWMA); it can de-emphasize older data points, if that is an issue.

As already commented by Majenko, the problem in integer wraparound. One solution would be to get rid of that total variable and calculate every new average based on the previous average and the mass you are replacing in the array, using this formula:

So your code would look like:

// convert to mass

// calculate the new average:

// advance to the next position in the array:

// if we're at the end of the array...
// ...wrap around to the beginning: