Cycles and average value

How to write a loop witch after X cycles adds values (for example from sensor connected to analog input) and calculate average ?

Use a for loop, addition and division.

int val;
int tot = 0;
int ave;
int cnt = 5;

for(int i=0; i<cnt; i++) // Loop cnt times
   val = analogRead(pin); // Read a value
   tot += val; // Sum the values
ave = tot/cnt;

Some things to watch out for include overflow in the tot variable and division by 0. Change tot to a long, if needed. Make sure cnt is never 0.

You might want to delay a little in the loop.

Some addition to PaulS code.

by using unsigned int the value before overflow is twice as high, needed if you take 15-30 33-64 samples. If you want to average still more samples use unsigned long.

To prevent division by zero you could use the compacted "if then else"

ave = (cnt > 0) ? tot / cnt : -1;  // prevents also negative counters.

A signed int will hold the sum of 30 readings in the 0 to 1023 range, easily. More than that, and a larger type, like unsigned int, may be required, depending on the average reading.

Your right Paul, :-[

For 1..32 samples a signed int works to summerize the samples. for 33..64 samples an unsigned int will do, and for more e.g. 100 you need to use an unsigned long.