Hi there, I have a distance sensor and I have been getting weird result when the results are printed.
On occasion, when I put objects in front of the sensor, sometime, the result are displayed in negative value.
As far, as I understand, analogRead() in arduino value are integer positive. Which means I should be getting values from 0 to 1023.
However, when I did sums of value and divide to get the average values, I get negative value.
Here is the following picture and code.
Now, to be honest, the sums of positive value are still positive. And real positive value convert to positive integer should still be positive...
What might cause the issue? I have checked the wiring, and they are well connected...
Thanks
//Small program calculating the average values, since the noise effect drastically alter value
int sum;
int j=150; //The number of iteration we want to have
int table[150];//Max table size
int i=100;
int average;
void setup() {
Serial.begin(9600);
}
//Procedure that calculate the mean value of a matrix
void Mean(){
sum=0;
//Taking 150 samples with a for loop, every iteration value from the analogRead are saved in a table
for (i=1;i<=j;i++){
delay(1);
table[i]=analogRead(A2);
sum=sum+table[i];
//Doing the sum as the iteration goes
}
//As the loop ended, we divided by 150.
average=sum/j;
}
void loop() {
Mean();
Serial.println(average);
//We want to this test continue, therefore we put this in a void loop
}