How to average the 5 past altitude values from the iPhone barometer

162 views Asked by At

I'm creating an application that displays the variation of altitude using the new iPhone6 barometer. Although the output data has noise so I would like to apply a 5 points moving average to smooth data.

Here is the code I have to calculate the altitude difference from the most recent timestamp to the previous timestamp.

CGFloat degree = (_altData.relativeAltitude.floatValue - _prevAltData.relativeAltitude.floatValue)

I need to store and retrive the additional 3 previous data and average them. Thanks in advance, I'm new to Xcode and this would really help.

1

There are 1 answers

0
AlexWien On

Store them in a fixed array of windowSize=5: somwhere when initializing your program:

// array of last altitudes for calculating average
int[] a = new int[windowSize];

1) When new data arrive store at last index:

a[windowSize - 1] = new_altitude,

2) calculate average.

   double avg = 0;
   for (int i = 0; i < windowSize; i++) {
      avg += a[i];
   }
   avg = avg / windowSize;

3) copy all array elements to current index - 1, so there is space for the next element.

for (int i = 1; i < windowSize; i++) {
  a[i-1] = a[i];
}

That's it.

In practise it can get very complex if the window is not completly filled, so just wait till you have your array completly filled before you output the average.

Depending on your App you may do step 3) as first step, thiw would have the advantage that the elements in a[] are always real existing data.
So th eorder of the steps 3), 1), 2) is a bit better on a puristic view.