Average of samples for voltage measurement

Hey Experts,
I am trying to measure dc voltage using arduinio. But the values that I'm get are very unstable. How do I take average of values to make them stable.
Here is the code,



int vin;
int input=A3;



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

}
void loop()
{

vin=analogRead(input);
vin=vin/2.046;
Serial.println(vin);
delay(300);

}


Try a digital filter:

unsigned int smooth(unsigned int newVal) {
  static unsigned int oldVal = 0;
  unsigned long sum;
    //  optimize sum = (oldVal * 3 + newVal) / 4;
    sum = ( (oldVal << 1) + oldVal + newVal) >> 2;
  }
  oldVal = sum;
  return oldVal;
}
...
  // example use
  smoothedValue = smooth( analogRead(A0) );

...

This is the same as (with moving the concept to float instead)

sum = 0.75 * oldVal + 0.25 * newVal;

"a big part of the old value plus a small part of the new value"

where we always have two coefficients which add up to one. 0.75 and 0.25 in the above. @anon57585045 uses integers and can therefor use shifting and adding instead of multiplying, which is slick but obscures the maths a bit.

You can effect the rate at which it will reach a steady agreement with an unchanging input by being more or less aggressive about how much the new influences the old, viz:

sum = 0.95 * oldVal + 0.05 * newVal;  // slower convergence

or

sum = 0.7* oldVal + 0.3 * newVal;  // more rapid

Play with it and watch the output.

a7

Just be sure the source values are changing, not just the readings due to improper design or layout... if you average those you are basically sweeping dirt under the carpet.

A/D value / 2.046?
500volt supply?

You should use one of the internal references of the Arduino for voltage measurements.
How, depends on which Arduino you're using.
Leo..

Thanks @alto777!!
Can you please structure in my code as I'm a beginner!!

Sure. This is your sketch (I use the IDE Autoformat tool on it, a habit you should develop), with @anon57585045's idea from post #2 above "structured in".

I did remove a stray closing brace } from that code.

When I tested it, it was more fun when I turned the speed up by using a shorter delay(30).

But you are getting a bit ahead of yourself. Please find a learning source and try to pick up the basics. Variable types and the use of functions, maybe after you get a grip on if/else statements and for and while loops.

int vin;
int input = A3;

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

void loop()
{
  vin = smooth(analogRead(input));
  vin = vin / 2.046;
  Serial.println(vin);
  delay(30);
}

unsigned int smooth(unsigned int newVal) {
  static unsigned int oldVal = 0;
  unsigned long sum;
    //  optimize sum = (oldVal * 3 + newVal) / 4;
  sum = ( (oldVal << 1) + oldVal + newVal) >> 2;

  oldVal = sum;
  return oldVal;
}

HTH

a7

Thanks mate!!!
It works wonderfully!!!!
Thanks for your constant support!!