system
April 22, 2013, 9:33pm
1
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[x] = analogRead(phototransistorPin1);
adcValue2[x] = analogRead(phototransistorPin2);
adcValue3[x] = analogRead(phototransistorPin3);
adcValue4[x] = analogRead(phototransistorPin4);
}
now I need the average of each adcValue
Thanks
What Arduino, or compatible, device is this running?
system
April 22, 2013, 9:46pm
3
I am using arduino mega 2560
Arrch
April 22, 2013, 9:47pm
4
Hard to say with bullet point style code
system
April 22, 2013, 9:53pm
5
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);
}
system
April 22, 2013, 10:01pm
6
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;
}
system
April 22, 2013, 10:44pm
7
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.
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.
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;
}