loading

How do I make arduino Add 5 numbers and spit out the average?

This is what I have so far. but its not working.. 

float average = 0;
int total = 0;
int n;



void setup(){
  Serial.begin(9600);
  while (Serial.available());
  for (n=0; n <=5; n++);
  total+=Serial.parseInt();
  average=total/5;
  Serial.println(average);

 
}

void loop () {
}

Libahunt3 years ago

Here is one way to do it.

It still has a quirk that if you enter numbers (and press enter) in short intervals, they can be read as digits of one bigger number.

<code>

float average = 0;
int total = 0;
int n;

void setup(){
Serial.begin(9600);
}

void loop () {

for (n=0; n<5; n++) {//you want to read a number five times

while (!Serial.available()) { //to read something you have to wait for it to be typed, ! means "not"
//do nothing while no input
}

//program gets out from previous while loop, when something became "available"
//now use it
total+=Serial.parseInt();
//Serial.println("total so far " + String(total)); //uncomment for debugging

}

//for loop ended when 5 inputs were received
average= total/5.0;//5.0 makes the calculation to the right of equation mark floating point
Serial.println(average);

//it will start over now, because the code is in loop, and therefore we have to reset total
total = 0;
//if you copy all contents of loop to the end on setup, it will run once

}

</code>

Ask, if my code comments are not sufficient to clarify what is going on.

mh76dk3 years ago

You are also adding up 6 numbers (your for-loop counts: 0, 1, 2, 3, 4, 5).

And from my limited understanding (based on http://forum.arduino.cc/index.php/topic,41809.0.h... of Serial.available() you would be stuck in that (empty -ending in a ';') while-loop as long as you have data - i am almost sure that is not what you intend to do.

Your for-loop is also empty and you need remove the ';' . And though I dont want to get into an argument about the optional curly braces, you should probably at least put the while-loop in a pair.

I hope i make sense and didnt get my facts and corrections wrong (its slightly late here)

mh76dk mh76dk3 years ago

Somehow the link got mangled...: http://forum.arduino.cc/index.php/topic,41809.0.html

Because you have everything in the setup. Move it to the loop where it belongs.