Go Down

Topic: array average (Read 474 times) previous topic - next topic

fred1091

Hi guys I need some help, I am fairly new to arduino, I have an array of 100 integers and I need the average of these integers, how can I do it?

This is my code;

for (int x = 0; thisPin < 100; x++)
  {
    adcValue1
  • = analogRead(phototransistorPin1);
        adcValue2
  • = analogRead(phototransistorPin2);
        adcValue3
  • = analogRead(phototransistorPin3);
        adcValue4
  • = analogRead(phototransistorPin4);
      }

    now I need the average of each adcValue
    Thanks

lloyddean

What Arduino, or compatible, device is this running?

fred1091

I am using arduino mega 2560

Arrch

Hard to say with bullet point style code

fred1091

I'm sorry that was just a typing error,

This is the code: for (int x = 0; x< 100; x++)
  {
    adcValue1= analogRead(phototransistorPin1);
    adcValue2= analogRead(phototransistorPin2);
    adcValue3= analogRead(phototransistorPin3);
    adcValue4= analogRead(phototransistorPin4);
  }

psppb


float runningTotal = 0;
float average = 0;
for (int x = 0; x< 100; x++)
  {
   
    adcValue1= analogRead(phototransistorPin1);
    runningTotal = adcValue1 + runningTotal;
    adcValue2= analogRead(phototransistorPin2);
    runningTotal = adcValue1 + runningTotal;
    adcValue3= analogRead(phototransistorPin3);
    runningTotal = adcValue1 + runningTotal;
    adcValue4= analogRead(phototransistorPin4);
     
   average = runningTotal/x;
   
  }

PeterH

Code: [Select]

for (int x = 0; thisPin < 100; x++)
{
    adcValue1[x] = analogRead(phototransistorPin1);
    adcValue2[x] = analogRead(phototransistorPin2);
    adcValue3[x] = analogRead(phototransistorPin3);
    adcValue4[x] = analogRead(phototransistorPin4);
}


You need to use [ code ] [ /code ] tags to stop the forum software from mangling your code.

To generate an average, add up all the samples and divide by the number of samples.
Code: [Select]

long total = 0;
for(int x = 0; x < 100; x++)
{
    total += analogRead(phototransistorPin1);
}
adcValue1 = total/100;


Since you're doing the same thing four times, it would make sense to use arrays to hold your pins and to hold the resulting averages.

Code: [Select]

const int NUM_PINS = 4;
const int phototransistorPin[NUM_PINS] = { 2, 3, 4, 5 }; // substitute whatever pins you're using

...


long average[NUM_PINS];
long total[NUM_PINS];
for(int pin = 0; pin < NUM_PINS; pin++)
{
  total[pin] = 0;
  for(int sample = 0; sample < 100; sample++)
  {
    total[pin] += analogRead(phototransistorPin[pin]);
  }
  average[pin] = total[pin]/100;
}
I only provide help via the forum - please do not contact me for private consultancy.


Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy