cancel
Showing results for 
Search instead for 
Did you mean: 

Doubt regarding Moving Average Problem is STM32

Killstreet30
Associate III

Hi,

I want to compute the moving average of an IR sensor and set the brightness of an LED and im taking input values from read and I have set up an a timer interrupt which gets triggered every 100ms, and with this trigger I'm saving the read values into an array of size 10. My window size is 10. When I'm running the values keep running very rapidly to infinity. Please help. Thank you. Please check the timer interrupt loop for moving average, I feel something is wrong there.

uint16_t read;

float MA[10];

float sum =0;

uint16_t i=0;

uint16_t j=0;

 while (1)

 {

  /* USER CODE END WHILE */

   HAL_ADC_Start(&hadc1);

   HAL_ADC_PollForConversion(&hadc1, 100);

   read = HAL_ADC_GetValue(&hadc1);

       if(sum >=2470 && sum <=2530){

        __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, 1000);

        }

        else if(sum>=999 && sum <=2470){

       __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, sum/5);

        }

        else if(sum >= 2530 && sum <=4095){

       __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, (5095-sum)/5);}

 }

}

}

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim){

float window_size = 10;

if(htim->Instance == TIM3){

MA[i%10] = read;

i=i+1;

for(j=0;j<10;j++){

sum = sum + MA[j]/window_size;

}

}

}

1 ACCEPTED SOLUTION

Accepted Solutions
gbm
Lead III

You forgot to set the sum to 0 before computing the running average.

My STM32 stuff on github - compact USB device stack and more: https://github.com/gbm-ii/gbmUSBdevice

View solution in original post

2 REPLIES 2
S.Ma
Principal

ADC sample can get triggered by a signal, which can be a pin.

A PWM can be generated by a TIMER and output to a pin.

Connect both pins with a wire.

now the PWM period must be longer than the ADC sample time (here time scale is far from the limits)

The DMA can store the ADC measured sample in a buffer (10 16-bit values), which can be written in cyclic mode. At any time you select, read the 10 samples and make the average. This should be the moving average.

There are many other ways to do it. This to me is HW assisted, works when cranked up in speed.

gbm
Lead III

You forgot to set the sum to 0 before computing the running average.

My STM32 stuff on github - compact USB device stack and more: https://github.com/gbm-ii/gbmUSBdevice