Hello,
First, I'm such a newbie! Second, I am working with 5 photocells which are connected to the arduino from A0 -A4. I am able to read the values and such. However, I have to average the top three values of the photocells.
For example:
Cell 1 = 100
Cell 2 = 600
Cell 3 = 200
Cell 4=300
Cell 5 = 500
I have to get the average of the top three, so 600+300+500. I am trying to put them in an array and sort the top three and get the average like that, however, I am having issues.
code that I have so far:
int analogPin0 = 0;
int analogPin1 = 1;
int analogPin2 = 2;
int analogPin3 = 3;
int analogPin4 = 4;
int number;
int analogreading = 0;
int analogreading1 = 1;
int analogreading2 = 2;
int analogreading3 = 3;
int analogreading4 = 4;
int list[] = { analogPin0, analogPin1, analogPin2, analogPin3, analogPin4 };
void setup()
{
Serial.begin(9600);
}
void loop()
{
analogreading = analogRead(analogPin0);
Serial.print("Pin0=" );
Serial.println(analogreading);
analogreading1= analogRead(analogPin1);
Serial.print("Pin1 =");
Serial.println(analogreading1);
analogreading2= analogRead(analogPin2);
Serial.print("Pin2 =");
Serial.println(analogreading2);
analogreading3= analogRead(analogPin3);
Serial.print("Pin3 =");
Serial.println(analogreading3);
analogreading4= analogRead(analogPin4);
Serial.print("Pin4 =");
Serial.println(analogreading4);
// number=(analogreading1 + analogreading2)/2;
// Serial.print("num=");
// Serial.println(number);
for (int i=3 ; i ; i--) {
for (int j=0 ; (j + i) < 5 ; j++) {
if (list[ j ] < list[ j + i ]) {
int t = list[ j ];
list[ j ] = list[ j + i ];
list[ j + i ] = t;
}
}
}
int sum = 0;
for (int k=0 ; k < 3 ; k++) {
sum += list[ k ];
}
float average = sum / 3.0;
Serial.print("avg=");
Serial.println(average);
delay(2000);
}
And the output is just:
Pin0=157
Pin1 =173
Pin2 =170
Pin3 =142
Pin4 =175
avg=3.00
Pin0=157
Pin1 =172
Pin2 =169
Pin3 =140
Pin4 =173
avg=3.00
The Average is remaining the same?
in the list the average should be 173 for the first one and 171 for the second?
Thank you so much for helping.