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);
}
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:
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.
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;
}