Unexpected negative values from abs() function inline with analogRead
abs() is defined in Arduino.h as a macro:

 #define abs(x) ((x)&gt;0?(x):-(x))


A macro does not evaluate in the same way as a function. 

 sensor = abs(analogRead(A0) - 512);


This statement will be expanded at compile-time to:

 sensor = ((analogRead(A0) - 512)&gt;0?(analogRead(A0) - 512):-(analogRead(A0) - 512));


Now the "error" is easy to understand. The analog pin is read twice. The "error" can be avoided by adding the following line first in your sketch:

#undef abs


This will remove the macro abs() and the standard library function will be used instead. 

Cheers!