How can i calculate a moving avarage in arduino?

I have to add a moving avarage to my program wich is working now with ultrasonic sensor with arduino. Here is my code:

#define USONIC_DIV 58.0
#define MEASURE_SAMPLE_DELAY 5
#define MEASURE_SAMPLES 25
#define MEASURE_DELAY 250
#define MEASURE
// Declarare variabile
int trigPin = 2;
int echoPin = 3;
int pingTravelTime;
int Buttonpin = 11;
int Buttonpin2 = 12;
int ButtonVal2 = 0;
int ButtonVal;
long int max = -10000;
long int min = 10000;
const int numReadings = 1000;
int readings[numReadings];
int readIndex = 0;
int total = 0;
int avarage = 0;
void setup() {
  /// Declararea pinilor de pe circuit
  Serial.begin(9600);
  pinMode(trigPin,OUTPUT);
  pinMode(echoPin,INPUT);
  pinMode(Buttonpin,INPUT);
  pinMode(Buttonpin2,INPUT);
  digitalWrite(trigPin,LOW);
  delayMicroseconds(500);
  digitalWrite(Buttonpin2,HIGH);
  digitalWrite(Buttonpin,HIGH);
  Serial.begin(9600);
  for(int i=0; i<numReadings; i++){
    readings[i]=0;
  }
}
void loop() {
  // Butonul de trigger pentru masuratori
  ButtonVal = digitalRead(Buttonpin);
  while(ButtonVal == 1){
    ButtonVal = digitalRead(Buttonpin);
  }
  // Reset button pentru valorile min/max
  ButtonVal2 = digitalRead(Buttonpin2);
  if(ButtonVal2 == LOW){
    max=0;
    min=0;
  }
  digitalWrite(trigPin,LOW);
  delayMicroseconds(10);
  digitalWrite(trigPin,HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin,LOW);
  pingTravelTime=pulseIn(echoPin,HIGH);
  delay(25);
  delay(MEASURE_DELAY);
  long distance = measure();
  // Afisarea valorilor in mm,DEC,BIN,HEX
  Serial.print(distance);
  Serial.println(" mm");
  Serial.print(pingTravelTime);
  Serial.print(" ");
  Serial.print(pingTravelTime,BIN);
  Serial.print(" ");
  Serial.print(pingTravelTime,HEX);
  Serial.print(" ");
  Serial.println(max);
  Serial.print(" ");
  Serial.println(min);
  Serial.print(" ");
  Serial.print("\n");
  delay(100);
}
// Functiile pentru convertirea valorilor DEC in mm
long measure()
{
  long measureSum = 0;
  for (int i = 0; i < MEASURE_SAMPLES; i++)
  {
    delay(MEASURE_SAMPLE_DELAY);
    measureSum += singleMeasurement();
  }
  return measureSum / MEASURE_SAMPLES;
}
long singleMeasurement()
{
  long duration = 0;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(11);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  return (long) (((float) duration / USONIC_DIV) * 10.0);
 
}`Preformatted text`

please edit your post, select the code part and press the </> icon in the tool bar to mark it as code. It’s unreadable as it stands. (also make sure you indented the code in the IDE before copying, that’s done by pressing ctrlT on a PC or cmdT on a Mac)

i’ve used leaky integration in speakerphones

avg += (measurement - avg) * K; // K < 1

https://www.arduino.cc/reference/en/libraries/moving-average-library/

When dealing with sensors that are prone to producing outliers, such as ultrasonic sensors, it’s often a good idea to use a median filter to get rid of these outliers.
For example: MedianFilter.ino

The same Arduino-Filters library also has many other types of filters, such as the moving average filter you asked for: SimpleMovingAverage.ino
The “leaky integrator” mentioned by gcjr is included under the name Exponential Moving Average filter (EMA).

You can easily compose these filters, e.g.:

#include <Filters/MedianFilter.hpp>        // MedianFilter
#include <AH/Filters/EMA.hpp>              // EMA

// [...] see MedianFilter example above

// Median filter of length 5, initialized with a value of 0.
MedianFilter<5, unsigned long> medfilt {0};
// Exponential moving average filter with a pole in 1 - 2⁻³ = 0.875,
// also initialized to 0.
EMA<3, unsigned long> emafilt {0};
 
void loop() {
  if (timer) { // returns true once every 10 ms, determines sampling frequency
    auto raw      = analogRead(A0);
    auto filtered = emafilt(medfilt(raw));
    Serial.println(filtered);
  }
}

it s done :smiley:

Can u pls write integrated in my code?

Why don’t you give it a try?
If you have any specific questions about the code I posted, or if you run into problems when adding it to your code, I’ll be happy to help.

If you dig around in this forum and look for moving average, you will find it has been covered before.
Basically, what you do is have an array of numbers the size of the number of values you want to average.
When a new value comes along, it joins the array and pushes the oldest value out.
I think there is or was a library called average.h that might help

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