Go Down

### Topic: array average (Read 1 time)previous topic - next topic

#### fred1091

##### Apr 22, 2013, 11:33 pm
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++)
{
}

now I need the average of each adcValue
Thanks

#### lloyddean

#1
##### Apr 22, 2013, 11:45 pm
What Arduino, or compatible, device is this running?

#### fred1091

#2
##### Apr 22, 2013, 11:46 pm
I am using arduino mega 2560

#### Arrch

#3
##### Apr 22, 2013, 11:47 pm
Hard to say with bullet point style code

#### fred1091

#4
##### Apr 22, 2013, 11:53 pm
I'm sorry that was just a typing error,

This is the code: for (int x = 0; x< 100; x++)
{
}

#### psppb

#5
##### Apr 23, 2013, 12:01 am

float runningTotal = 0;
float average = 0;
for (int x = 0; x< 100; x++)
{

average = runningTotal/x;

}

#### PeterH

#6
##### Apr 23, 2013, 12:44 am
Code: [Select]

for (int x = 0; thisPin < 100; x++)
{
}

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++)
{
}

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++)
{