Creating an Average for Serial Monitor

Hello, I’m trying to take an average from the serial monitor of about 100 samples to eliminate some of the noise. Here is what I have so far and it is only a part of my whole code:

 void loop() 
{
  
  int readings[5];
  
  int i;
  
  int sensorValue = analogRead(sensorPin);
  
  float voltage = sensorValue * (5.0 / 1023.0);
  
  for(i=0; i<5; i++)
  {
   readings[i] = voltage;
  }
  
  int avgReading = (readings[0] + readings[1] + readings[2] + readings[3] + readings[4])/5; 
  
  Serial.println(avgReading, 3);
  
  delay(50);

When I execute that part right there, the serial monitor is printing all zeros. What am I doing wrong here? Also, I would like to take 100 samples and take the average of those, but with my method here, it would take a while to code. Is there an easier way to do it? Thank you very much!

Also, I would like to take 100 samples and take the average of those, but with my method here, it would take a while to code.

A “for” loop and a variable large enough to contain 102 300.

 readings[i] = voltage;

Assigning a float to an int makes no sense whatsoever.
The thing you should be averaging is the raw readings.

  for(i=0; i<5; i++)
  {
   readings[i] = voltage;
  }
  
  int avgReading = (readings[0] + readings[1] + readings[2] + readings[3] + readings[4])/5;

Adding up n 5 times, and then dividing by 5 is not giving you an average. It’s just wasting time.

To average 5 readings, you need to take 5 readings.

try this

void loop() 
{
  float sum = 0;
  for(int i=0; i< 5; i++)
  {
    sum = sum + analogRead(sensorPin);
    delay(100);  // to average over a longer time period the delay is in the for loop
  } 

  float average = sum / 5.0 ;
  float voltage = average * 5.0 / 1023;  

  Serial.println(voltage, 3);
}

long sum = 0; would save some time.

float average = sum / 5.0 ;
  float voltage = average * 5.0 / 1023;

Or even just:

  float voltage = sum / 1023.0;

or even

float voltage = sum * 0.000977517; // multiplication is faster than divide :wink: