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
}
gcjr
July 9, 2022, 10:25am
3
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 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..
GolamMostafa:
A typical example:
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....
1 Like
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?
bigdingo:
‘abs’
Absolute. abs(-5) = 5, abs(5) = 5 ... so always returns a positive value.
bigdingo:
‘||’ mean
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;
The Arduino programming language Reference, organized into Functions, Variable and Constant, and Structure keywords.
The Arduino programming language Reference, organized into Functions, Variable and Constant, and Structure keywords.
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...
5 x 1023 ~ 5 000. Maximum of int ~ 30 000. AFAIK 5 000 < 30 000, it should fit easily.
Smajdalf:
Maximum of int ~ 30 000.
Maximum of int ~30 000 32767.
gcjr
July 11, 2022, 11:21am
19
do you understand what the tilde "~" means?