Serial Prints Average Sensor Read

Hi All! I am using a photodiode to take measurements of an LED but am overwhelmed by the outputs. For each blink, I want the photodiode to take 5 readings and print out the average of the five. I figured out how to get it to take 5 readings, but I don't know how to get the serial monitor to only show the average of them. Any help?

//Initializing LED pin/sensor
int led_pin = 6;
int sensorPin = A0;
int sensorValue = 0;
void setup() {
Serial.begin(9600);
pinMode(sensorPin, INPUT); //sensor input
pinMode(led_pin, OUTPUT); //led input
}
void loop() {

for(int i=0; i<5; i++){
digitalWrite(led_pin, HIGH); // LED on
delay(3);
sensorValue = analogRead(sensorPin);
Serial.println(sensorValue);
}

for(int i=0; i<250; i++){
digitalWrite(led_pin, HIGH); // LED on
delay(3);
}

for(int i=5; i>0; i--){
digitalWrite(led_pin, LOW); //LED off
delay(3);
sensorValue = analogRead(sensorPin);
Serial.println(sensorValue);
}

for(int i=250; i>0; i--){
digitalWrite(led_pin, LOW); //LED off
delay(3);
}
}

  • Initialise the total to zero
  • Each time you take a reading add it to the total
  • When you have read and totalled 5 values divide the total by 5
  • Print the result

Hi @zoesperduto

Recommendations.
Read: How to get the best out of this forum
Use </> tags to post sketcks or printouts;
What products are you using in your project?
Which microcontroller you using in your project?
Arduino Uno/Mega/ESP....?

RV mineirin

Try this sketch:

//Initializing LED pin/sensor
int led_pin = 6;
int sensorPin = A0;
int sensorValue = 0;
void setup() {
  Serial.begin(9600);
  pinMode(sensorPin, INPUT); //sensor input
  pinMode(led_pin, OUTPUT); //led input
}
void loop() {
  digitalWrite(led_pin, HIGH); // LED on
  for (int i = 0; i < 5; i++) {
    delay(3);
    sensorValue = sensorValue + analogRead(sensorPin);
  }
  Serial.println(sensorValue / 5);
  sensorValue = 0;
  digitalWrite(led_pin, LOW); //LED off
  for (int i = 5; i > 0; i--) {
    delay(3);
    sensorValue = sensorValue + analogRead(sensorPin);
  }
  Serial.println(sensorValue / 5);
  sensorValue = 0;
}

Arduino moving average filter.

This works! Thank you so much! I am very new to Arduino so this was super helpful.