# SOLVED: Problem with Averaging function

Hey guys! Over lockdown, I was playing around with my arduino and some sensors that I had lying around. This is really my first time trying to create anything using an arduino so it was a bit of an uphill battle.

The goal of the project was to get readings from an accelerometer, get an average and then print it. I got the first part done, however I ran into a roadblock when I tried to get an average (code below). I know for a fact that ax, ay, az and ox, oy, oz output the correct values. The issue comes when I try to calculate sumx, sumy and sumz.

Everywhere I’ve looked where they had a code tutorial to calculate an average they had it be:

``````sum = sum + (reading);
``````

which is exactly the way I have it set up. But whenever I run my code it always prints “0.00”.

Your help is greatly appreciated =)

``````#include <MPU6050.h>

#include <Wire.h>
MPU6050 accelgyro;
int16_t ax, ay, az, gx, gy, gz;
float ox, oy, oz;

void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Wire.begin();
accelgyro.initialize();
}

void smooth (int wsize) {
double sumx;
double sumy;
double sumz;

sumx = 0.00;
sumy = 0.00;
sumz = 0.00;

for (int i; i <= wsize; i++) {
accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
ox = ax / 16384.00;
oy = ay / 16384.00;
oz = az / 16384.00;

sumx = sumx + ox;
sumy = sumy + oy;
sumz = sumz + oz;
}

Serial.print(sumx/wsize);
Serial.print("\t");
Serial.print(sumy/wsize);
Serial.print("\t");
Serial.println(sumz/wsize);
}

void loop() {
// put your main code here, to run repeatedly:
Wire.beginTransmission(0x68);
smooth(10);

}
``````
``````Serial.print(sumx/(wsize +1));
``````

Also, you need to initialise your for loop control variable “i”

``````for (int i = 0; i <= wsize; i++) {
``````
``````void smooth (int wsize) {
double sumx;
double sumy;
double sumz;

sumx = 0.00;
sumy = 0.00;
sumz = 0.00;
``````

Don’t do this - there are no prizes for lengthy code.

``````void smooth (int wsize) {
double sumx = 0.0;
double sumy = 0.0;
double sumz = 0.0;
``````

These:

``````void smooth (int wsize) {
double sumx;
double sumy;
double sumz;
``````

Can ONLY be see by the function they are in. Move them to somewhere above setup().
Paul

TheMemberFormerlyKnownAsAWOL:

``````Serial.print(sumx/(wsize +1));
``````

Also, you need to initialise your for loop control variable “i”

``````for (int i = 0; i <= wsize; i++) {
``````
``````void smooth (int wsize) {
``````

double sumx;
double sumy;
double sumz;

sumx = 0.00;
sumy = 0.00;
sumz = 0.00;

``````

Don't do this - there are no prizes for lengthy code.

``````

void smooth (int wsize) {
double sumx = 0.0;
double sumy = 0.0;
double sumz = 0.0;

Thank you! I completely missed the fact that I needed to initialize the variable i in that loop! Frankly feel dumb that I didnt catch it myself.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.