Go Down

Topic: Why am I getting negative numbers? (Read 1 time) previous topic - next topic


This is my first Arduino project and I've never programmed before so some help would be much appreciated...

I'm reading three AC voltages and trying to average them out. The code below should only return positive numbers as I have used the ABS command, but I'm still getting negative numbers in the mix. What am I doing wrong?

Code: [Select]

const int numReadings = 50;
int bluetotal = 0;                  // the running total
int redtotal = 0;                  // the running total
int greentotal = 0;                  // the running total

int red = A0;
int green = A1;
int blue = A2;
void setup()
  // initialize serial communication with computer:


void loop() {
  // Take average of red blue and green                   
for (int count = 0; count < numReadings; count++) {
  bluetotal += abs(analogRead(blue));
  greentotal += abs(analogRead(green));
  redtotal += abs(analogRead(red));
  // send it to the computer as ASCII digits
   Serial.print("        "); 
   Serial.print("        "); 


You need to use the long type for your redtotal/greentotal/bluetotal variables, they are overflowing.

The output of analogRead is in the range 0..1023 inclusive and cannot be negative anyway.
[ I will NOT respond to personal messages, I WILL delete them, use the forum please ]


You might want to pay attention to this part of the abs() reference page (http://arduino.cc/en/Reference/Abs):
"Because of the way the abs() function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results."

I believe analogRead() would qualify as a function...
Capacitor Expert By Day, Enginerd by night.  ||  Personal Blog: www.baldengineer.com  || Electronics Tutorials for Beginners:  www.addohms.com


Thanks for the quick response, Can you explain what you mean by Long Type?
I still find it unusual that I am getting negative numbers in the output, especially if the readings are all positive number.


Thanks guys, Figured it out. Moved the Long initialiser into the main loop as well and am getting correct readings now!


Type int can hold values of up to between -32767 and 32768 you are adding 50 values of up to 1023 which can overrun 32768 and push the value into the negative range of the variable. If you read the reference to the arduino language it explains what 'long' type is.  It can hold a much larger number before it overflows in simple terms.  You could get away with 'unsigned int' which cannot give negative values and doesn't overflow until it gets past 65535.

Go Up