I am trying to average input values for a number of inputs and have it then store those averages into a string to write to a txt doc on a sd card.

I am using:

// read 6 sensors and append to the string:
for (int analogPin = 0; analogPin < 6; analogPin++) {
  int sensor = analogRead(analogPin);
  dataString += String(sensor);
  if (analogPin < 6) {
    dataString += ",";

to read the pins at the moment, but I want to change the analogRead(analogPin) to an average value and then use the averages to create the string.

but when I try to average the data I run into errors, or I get output that is 0 for something that should be higher (3.3V).

I am doing this to stabilize my values a bit better and remove jitter.

Any suggestions?


1 Answer 1


This function will average readings on an analog pin, include it and use it in place of analogRead(...) and it should do what you want.

int aveAnalogRead(int pin, int ave=10, int delayms = 0)
    int tot = 0;
    for(int i=0; i<ave; i++)
        tot += analogRead(pin);
        if(delayms) delay(delayms);
    return tot/ave;

in your loop():

for (int analogPin = 0; analogPin < 6; analogPin++) 
   int sensor = aveAnalogRead(analogPin);
     <<do your work here>>
  • 1
    There is almost never a good reason to add a delay. Jun 21, 2018 at 9:10
  • With this though I have to run it multiple times, one for each input. Is it possible to have it also cycle though the inputs such as a loop within a loop?
    – Michael H.
    Jun 21, 2018 at 13:42
  • yes use it inplace of your analogInput call above loop within a loop
    – esoterik
    Jun 21, 2018 at 14:04
  • so this:int pin, for (int n=0, n<10, n++){ pin = n; int aveAnalogRead( int ave=10, int delayms = 50) { int tot = 0; for(int i=0; i<ave; i++) { tot += analogRead(pin); delay(delayms); } return tot/ave; }}
    – Michael H.
    Jun 21, 2018 at 14:39
  • that's not how C++ works; you put this function somewhere outside your loop() on your sketch, then call then function. you don't need to copy the definition of the function to call it.
    – esoterik
    Jun 21, 2018 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.