Inconsistent analog values

Hello,

I am working on a project using analog data, and have found some inconsistencies. Since my code is a bit strange if you aren't familiar if the project. I'm looking a the simple functions within my code.

I've noticed that when I print A0 with the average subtracted and the absolute value of the latter, I get different integers (besides the negative sign). Sometime they are both right (the same integers), and sometime they are close but not quite exact. I need a lot of precise for this project. Anythoughts? It might be easier to see what I am trying to explain if you run it yourself.

int sensorPin = A0;

int average = 2000;

int sensorValue = 0;

void setup() {

  // initialize the serial communication:

  Serial.begin(9600);

}



void loop() {

  // send the value of analog input 0:
/*
  Serial.println(analogRead(A0));
    Serial.print("//");
      Serial.println(analogRead(A0)-average);
      */
        Serial.println(analogRead(A0)-average);
    Serial.print("//");
   Serial.println(abs(analogRead(A0)-average));

  // wait a bit for the analog-to-digital converter 

  // to stabilize after the last reading:

  delay(1000);
  
  

}

abs is a macro.

What Coding Badly means, I think, is that this:

   Serial.println(abs(analogRead(A0)-average));

is not the same as this:

   int temp = analogRead(A0)-average ;
   Serial.println(abs(temp));

because analogRead(A0) does not necessarily return the same value twice in a row, and the abs(...) macro causes evaluation to take place twice.

Precisely. Well stated.

What do you mean by macro?

And thank you for the suggestion, however I tried making that adjustment and saw no difference.

adbc22:
What do you mean by macro?

https://www.google.com/search?q=what+is+a+c+macro

https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Arduino.h#L94

And thank you for the suggestion, however I tried making that adjustment and saw no difference.

I am struggling to find your new code. Perhaps you forgot to post it.

Call analogRead () once and assign that value to a variable. Then do all of your calculations and Serial.println (), etc. with the variable.