Nov 19, 2020

[Arduino code] Moving average filter (아두이노에서 구현한 이동평균 필터)

- Simple Arduino code to implement a moving average filter
- 이동평균 필터를 구현한 아두이노 코드
#define baud_rate 9600
#define low_window_size 5
#define high_window_size 20
//...
//...
int low_index = 0;
int high_index = 0;

float low_readings[low_window_size];
float high_readings[high_window_size];

float low_sum_measurement = 0;
float high_sum_measurement = 0;

float low_avg_measurement = 0;
float high_avg_measurement = 0;


void setup()
{
  
  //...
  //...
 Serial.begin(baud_rate); 
 //initialize **************************************************************
  for(int i = 0; i<low_window_size; i++){
    low_readings[i] = 0;
  }
  for(int k = 0; k<high_window_size; k++){
     high_readings[k] = 0;
  }
 
}

void loop()
{

  //...
  //...

  //moving average filter ***************************************************
  low_sum_measurement = low_sum_measurement - low_readings[low_index];
  high_sum_measurement = high_sum_measurement - high_readings[high_index];

  // sensor measurement
  low_readings[low_index] = measurement;
  high_readings[high_index] = measurement;
  
  low_sum_measurement = low_sum_measurement + low_readings[low_index];
  high_sum_measurement = high_sum_measurement + high_readings[high_index];
  
  low_index = low_index + 1;
  high_index = high_index + 1;

  if(low_index>=low_window_size){
    low_index = 0;
  }
  if(high_index>=high_window_size){
    high_index = 0;
  }

  low_avg_measurement = low_sum_measurement/low_window_size;
  high_avg_measurement = high_sum_measurement/high_window_size;
  
  // serial display ********************************************************
  Serial.print(measurement); Serial.print(", ");
  Serial.print(low_avg_measurement); Serial.print(",  ");
  Serial.print(high_avg_measurement);
  Serial.println();

}

As 'window size' increases, noise decreases but a time delay occurs.
window size 가 커질수록 노이즈는 줄어들지만 시간 지연 현상이 발생한다.

No comments:

Post a Comment