i think i heard my Arduino attempt to scream... ![]()
i'm trying to use a moving average of a sensor data (Accelerometer) to smooth out the values from analogRead(A2);
here's the code i used;
/*
AnalogReadSerial
Reads an analog input pin, prints the result to the serial monitor.
*/
int oldAvg[10] = {512, 512, 512, 512, 512, 512, 512, 512, 512, 512};
int newAvg[10];
int movit;
int calcit;
void setup() {
Serial.begin(9600);
}
void loop() {
for (int i=0; i<9; i++) {
movit=oldAvg[i+1];
newAvg[i]=movit;
}
newAvg[9]=(analogRead(A2))*5/3; // expand the resolution, i think the sensor operates on 3.3 V ...
/*
Serial.print("analogRead(A2)= ");
Serial.print(analogRead(A2));
Serial.print("*5/3 = ");
Serial.println(newAvg[9]);
*/
for (int i=0; i<10; i++) {
// calcit=+newAvg[i]; THIS DOESN'T WORK IN Arduino IDE ??
calcit = calcit + newAvg[i];
}
int sensorValue=calcit/10;
oldAvg[10] = newAvg[10]; // THIS IS THE CULPRIT
calcit = 0;
Serial.println(sensorValue);
delay(100); // delay in between reads for stability **using moving average, delay can be shortened
}
after a few loops, the reading just levelled (or maxed !) at 1023 and wouldn't budge - i spend a lot of time trying to find out where i might have made an error, and only after rebuilding the code bit by bit, i found the problem line.
after changing it to;
for (int i=0; i<10; i++) {
oldAvg[i] = newAvg[i]; // assign the members one at a time
}
all was fine.
the Verify process didn't have problems with assigning an array directly to another in one line, so what happened in the original code that pissed the Arduino off ?
also, is the code as efficient as possible already - are there faster functions to manipulate arrays like push or pop which i've seen used in some other high-level language but wasn't able to find it with a cursory browse though php.net or cplusplus.com