# Question about basic smoothing example from arduino

**URL:** <https://forum.arduino.cc/t/question-about-basic-smoothing-example-from-arduino/963309>\
**Category:** General Guidance\
**Created:** [February 25, 2022, 11:22am UTC](https://forum.arduino.cc/t/question-about-basic-smoothing-example-from-arduino/963309 "2022-02-25T11:22:54Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![zheygrudov](https://avatars.discourse-cdn.com/v4/letter/z/ed8c4c/32.png) [@zheygrudov](https://forum.arduino.cc/u/zheygrudov)\
**Post date:** [February 25, 2022, 11:22am UTC](https://forum.arduino.cc/t/question-about-basic-smoothing-example-from-arduino/963309/1 "2022-02-25T11:22:54Z")

</div>

My interpretation of the code of [the smoothing example](https://create.arduino.cc/example/builtin/03.Analog%5CSmoothing/Smoothing/preview), is that each iteration of loop the latest sensor reading `(t)` is added to a running total, and the` t - 1` reading is subtracted from the total. For a running average, shouldn't the oldest sensor reading be subtracted instead? I'm probably missing something really basic..

I was looking through these examples to try to find an efficient way to implement a weighted moving average for sensor data (both positive and negative from an IMU) in float.

I have this:

```cpp
  float x_avg = 0;
  float y_avg = 0;
  x_avg *= 0.75;
  x_avg += 0.25 * x_reading;
  y_avg *= 0.75;
  y_avg += 0.25 * y_reading;

```

But apparently this is bad practice / really slow?

p.s. I found [this class](https://tttapa.github.io/Pages/Mathematics/Systems-and-Control-Theory/Digital-filters/Exponential%20Moving%20Average/C++Implementation.html#arduino-example), but the author cautions it doesn't work for negative numbers (I think). You

---

<div class="post-metadata">

**Author:** ![anon73444976](https://avatars.discourse-cdn.com/v4/letter/a/439d5e/32.png) [@anon73444976](https://forum.arduino.cc/u/anon73444976)\
**Post date:** [February 25, 2022, 11:31am UTC](https://forum.arduino.cc/t/question-about-basic-smoothing-example-from-arduino/963309/2 "2022-02-25T11:31:34Z")

</div>

> [@zheygrudov](#):
>
> My interpretation of the code of [the smoothing example](https://create.arduino.cc/example/builtin/03.Analog%5CSmoothing/Smoothing/preview), is that each iteration of loop the latest sensor reading `(t)` is added to a running total, and the` t - 1` reading is subtracted from the total.

Your interpretation is incorrect.  
The oldest reading _is_ subtracted, not the previous reading - it's a circular buffer

> [@zheygrudov](#):
>
> But apparently this is bad practice?

I'd maybe add 25% of the new reading to 75% of the running average, and not the other way round

---

<div class="post-metadata">

**Author:** ![zheygrudov](https://avatars.discourse-cdn.com/v4/letter/z/ed8c4c/32.png) [@zheygrudov](https://forum.arduino.cc/u/zheygrudov)\
**Post date:** [February 25, 2022, 11:40am UTC](https://forum.arduino.cc/t/question-about-basic-smoothing-example-from-arduino/963309/3 "2022-02-25T11:40:22Z")

</div>

Thanks for responding. Don't want to take too much of your time, but just in case you look at this. I still don't understand why. For example when the readindex is at 4, we add the latest sensor reading to the total (and save it at index 4) and subtract the reading which was saved at readindex 3, which is from the previous sensor read?

Thanks for the note on the 2nd example. Is there a way to get around multiplication/division to speed up the code. I'm still quite new at this, but I read that maths in floats is very slow.

---

<div class="post-metadata">

**Author:** ![anon73444976](https://avatars.discourse-cdn.com/v4/letter/a/439d5e/32.png) [@anon73444976](https://forum.arduino.cc/u/anon73444976)\
**Post date:** [February 25, 2022, 11:56am UTC](https://forum.arduino.cc/t/question-about-basic-smoothing-example-from-arduino/963309/4 "2022-02-25T11:56:23Z")

</div>

You're not thinking in a circular fashion.  
Start at index zero, and see what happens.

> [@zheygrudov](#):
>
> For example when the readindex is at 4, we add the latest sensor reading to the total (and save it at index 4) and subtract the reading which was saved at readindex 3, which is from the previous sensor read?

When the index is at four, you subtract the reading at four from the total, write the new reading at four, add the new reading to the total, and then increment the index for the next time around the loop.

(Also, the for loop in the setup function is superfluous)

---

<div class="post-metadata">

**Author:** ![Koepel](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/koepel/32/637546_2.png) [@Koepel](https://forum.arduino.cc/u/Koepel)\
**Post date:** [February 25, 2022, 12:20pm UTC](https://forum.arduino.cc/t/question-about-basic-smoothing-example-from-arduino/963309/5 "2022-02-25T12:20:33Z")

</div>

What kind of data do you want to smooth ?

As TheMemberFormerlyKnownAsAWOL already wrote, the smooth example is correct. It is a mathematical trick and it removes the oldest sample.  
This is the actual tutorial: [https://www.arduino.cc/en/Tutorial/BuiltInExamples/Smoothing](https://www.arduino.cc/en/Tutorial/BuiltInExamples/Smoothing)

For high frequency electronic noise, it is enough to take a number of samples without the need of an array. See my example: [averageRead.ino](https://gist.github.com/Koepel/f7d625a6e5c0481fc4c7a9c530c643ef)  
For example when reading a voltage from a battery, then that is enough.

For a sensor with a acceleration, gyro, magnetometer, there are a number of mathematical filters, such as AHRS. It works very well because of Sensor Fusion (the disadvantages of each sensor is compensated by the other sensors).

A simple low-pass filter with a float variable is as you showed. Often 1% or less of the new data is used for the average.

```cpp
// global variable for average
float average;

// in the loop()
  int rawADC = analogRead();
  float newValue = (float) rawADC;
  average = (0.99 * average) + (0.01 * newValue);

```

That works really well, and no array is needed. It can be used in combination with a millis-timer, to get a new sample every 10ms for example.

Reducing the mains 50Hz or 60Hz is not so easy. Trying to reduce that noise with shielding or a hardware filter might be needed.

What I wrote here is just a very small part of the smoothing possibilities. It depends on your project what the best smoothing is.

---

<div class="post-metadata">

**Author:** ![anon57585045](https://avatars.discourse-cdn.com/v4/letter/a/ed8c4c/32.png) [@anon57585045](https://forum.arduino.cc/u/anon57585045)\
**Post date:** [February 25, 2022, 12:31pm UTC](https://forum.arduino.cc/t/question-about-basic-smoothing-example-from-arduino/963309/6 "2022-02-25T12:31:16Z")

</div>

Yes, and that form of low pass filter can easily be made using only integer arithmetic, or even bit shifting in some cases - making it tens or hundreds of times faster.

---

<div class="post-metadata">

**Author:** ![zheygrudov](https://avatars.discourse-cdn.com/v4/letter/z/ed8c4c/32.png) [@zheygrudov](https://forum.arduino.cc/u/zheygrudov)\
**Post date:** [February 25, 2022, 12:35pm UTC](https://forum.arduino.cc/t/question-about-basic-smoothing-example-from-arduino/963309/7 "2022-02-25T12:35:53Z")

</div>

I see now, couldn't get the logic on my own. Thank you!

---

<div class="post-metadata">

**Author:** ![zheygrudov](https://avatars.discourse-cdn.com/v4/letter/z/ed8c4c/32.png) [@zheygrudov](https://forum.arduino.cc/u/zheygrudov)\
**Post date:** [February 25, 2022, 12:40pm UTC](https://forum.arduino.cc/t/question-about-basic-smoothing-example-from-arduino/963309/8 "2022-02-25T12:40:23Z")

</div>

Thank you, @Koepel for taking the time to reply.  
Lots of useful info. It's basically angular velocity vectors, which are rotated by quaternions that I get from sensor fusion. These angular velocity vectors, are going to serve as inputs for the mouse library to move the mouse around. But I'm trying to smooth them out bit, so the device feels better to use. I think I should have been clearer, that what I'm trying to accomplish is to basically find a way to to the weighted average in some other way than float multiplication, since I read that's slow.

@anon57585045 Wow, that's a huge difference. Would you be able to share some link for this?

---

<div class="post-metadata">

**Author:** ![Koepel](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/koepel/32/637546_2.png) [@Koepel](https://forum.arduino.cc/u/Koepel)\
**Post date:** [February 25, 2022, 12:56pm UTC](https://forum.arduino.cc/t/question-about-basic-smoothing-example-from-arduino/963309/9 "2022-02-25T12:56:58Z")

</div>

With integers, keep the actual number in bits somewhat to the left and use the lower bits as bits behind the decimal dot.

Which library do you use ? Please give a link to it.

👉 It starts with a good sensor 👈  
I hope you are not using a fake, old, noisy MPU-6050 😱  
Do you use a 5V (Pro) Micro board with a 3.3V sensor ? then you should fix the voltage mismatch of the I2C bus.

---

<div class="post-metadata">

**Author:** ![zheygrudov](https://avatars.discourse-cdn.com/v4/letter/z/ed8c4c/32.png) [@zheygrudov](https://forum.arduino.cc/u/zheygrudov)\
**Post date:** [February 25, 2022, 1:23pm UTC](https://forum.arduino.cc/t/question-about-basic-smoothing-example-from-arduino/963309/10 "2022-02-25T13:23:44Z")

</div>

@Koepel thank you again for replying. I'm using a BMX160 sensor and an arduino nano. [This library](https://github.com/drcpattison/BMX160). Sorry I'm a bit of a newbie, still not sure how I would implement your advice. I'm more than happy to look at some link/do research, just not sure where to start.

---

<div class="post-metadata">

**Author:** ![anon57585045](https://avatars.discourse-cdn.com/v4/letter/a/ed8c4c/32.png) [@anon57585045](https://forum.arduino.cc/u/anon57585045)\
**Post date:** [February 25, 2022, 1:50pm UTC](https://forum.arduino.cc/t/question-about-basic-smoothing-example-from-arduino/963309/11 "2022-02-25T13:50:15Z")

</div>

> [@zheygrudov](#):
>
> Wow, that's a huge difference. Would you be able to share some link for this?

```arduino
unsigned int smooth(unsigned int newVal) {
  static unsigned int oldVal = 0;
  unsigned long sum;
    // optimize sum = (oldVal * 3 + newVal) / 4;
    sum = ( (oldVal << 1) + oldVal + newVal) >> 2;
  }
  oldVal = sum;
  return oldVal;
}
...
  // example use
  smoothedValue = smooth( analogRead(A0) );

...

```

For signed integer use, the bit shift part won't work. Make the variables signed and use:

```arduino
 optimize sum = (oldVal * 3 + newVal) / 4;

```

---

<div class="post-metadata">

**Author:** ![MarkT](https://avatars.discourse-cdn.com/v4/letter/m/c89c15/32.png) [@MarkT](https://forum.arduino.cc/u/MarkT)\
**Post date:** [February 25, 2022, 2:21pm UTC](https://forum.arduino.cc/t/question-about-basic-smoothing-example-from-arduino/963309/12 "2022-02-25T14:21:36Z")

</div>

> [@zheygrudov](#):
>
> ```arduino
> float x_avg = 0;
> float y_avg = 0;
> x_avg *= 0.75;
> x_avg += 0.25 * x_reading;
> y_avg *= 0.75;
> y_avg += 0.25 * y_reading;
> 
> ```

Those x\_avg and y\_avg variables need to be static so they persist globally.

You can code it as:

```arduino
  x_avg += 0.25 * (x_reading - x_avg) ;
  y_avg += 0.25 * (y_reading - y_avg) ;
```

Makes it easier to change the filter pole as only one constant has to be changed and also only one multiply is needed per variable.

---

<div class="post-metadata">

**Author:** ![zheygrudov](https://avatars.discourse-cdn.com/v4/letter/z/ed8c4c/32.png) [@zheygrudov](https://forum.arduino.cc/u/zheygrudov)\
**Post date:** [February 25, 2022, 7:58pm UTC](https://forum.arduino.cc/t/question-about-basic-smoothing-example-from-arduino/963309/13 "2022-02-25T19:58:13Z")

</div>

@aarg Thank you for sharing. I'll test these in a few examples tomorrow.

@MarkT thanks Mark, I'll test this tomorrow and use going forward.

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [August 24, 2022, 7:58pm UTC](https://forum.arduino.cc/t/question-about-basic-smoothing-example-from-arduino/963309/14 "2022-08-24T19:58:59Z")

</div>

Closed on August 24, 2022, 7:58pm UTC

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