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?
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:
Serial.begin(9600);
}
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(bluetotal/numReadings);
Serial.print(" ");
Serial.print(redtotal/numReadings);
Serial.print(" ");
Serial.println(greentotal/numReadings);
}
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...
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.
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.