Comparing Analog Inputs

Hello,

I would like to compare 2 analog inputs and take the average as a variable to use elsewhere in my code.

I would also like to compare the two inputs and if they vary by more than say 5% then do something else….

I am all good with the maths code for averaging the inputs but unsure how to compare two variables as part of an if() statement.

Is anyone able to assist, please?

Best,

Matt

Something like

if (valA < valB - 50) || valA > valB + 50)
{
  Do something 
}

consider

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

// -----------------------------------------------------------------------------
void
loop ()
{
    int  val0 = analogRead (A2);
    int  val1 = analogRead (A1);

    if (abs(val1 - val0) > (0.05 * val0))
        Serial.println ("diff");

    delay (1000);
}

I wanted to stay away from the floating point calculation :wink: hence the hard-coded values.

2 Likes

A typical example:

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

void loop()
{
  int vA0 = analogRead(A0);
  int vA1 = analogRead(A1);
  (vA0 > vA1) ? Serial.println(vA0): Serial.println(vA1);
  delay(1000);
}


1 Like

Hi, Sorry..

No it isn't, who would typically write it like that?

@bigdingo is obviously needing help with comparison functions, why confuse the issue with shorthand?

Tom.... :smiley: :+1: :coffee: :australia:

1 Like

Noted with thanks.

1 Like

What does ‘abs’ mean/do?

Why would you want to stay away from floating point calculations?

My understanding is that analogRead returns an integer?

Does the ‘||’ mean that either of those statements can be true to activate the if statement or both?

Absolute. abs(-5) = 5, abs(5) = 5 ... so always returns a positive value.

Logical OR... so yes, if either value is true.

It does... and the 2 examples above are similar, one calculates a % (0.05) difference (5%) to come up with an integer to compare to, the other just states the value to compare to (50 higher or lower).

It's more expensive in CPU time. Most Arduinos don't have floating point in hardware so the calculations are done in software. If you want a more efficient calculation for 5% first multiply your reading by 5 and next divide the result by 100. Note that 5 x1023 does not fit in an integer (on 8 bit processors) so you will have to use an unsigned integer or a long variable.

Hi, @bigdingo
If you Goolge;

arduino abs

and

arduino comparison

or

arduino ||

You get;

Simple really, Google it, you will save time.
We are here to help, but simple commands can be googled and tutorials or references appear.

Tom... :smiley: :+1: :coffee: :australia:

:+1:

@TomGeorge

5 x 1023 ~ 5 000. Maximum of int ~ 30 000. AFAIK 5 000 < 30 000, it should fit easily.

sh.t, you're right :frowning:

Maximum of int ~30 000 32767.

do you understand what the tilde "~" means?

approximately?