Hello,
I am trying to smooth readings from a pot but when I upload the sketch to arduino nano, I get a strange character reading, can you please help me do this because I never used an array as an index for a function. So I need to know where is my mistake.
my sketch is based on this example from the arduino tutorials but I am trying to build a function that can be usable again
here is my sketch:
const int numReadings = 10;
int readings[numReadings]; // the readings from the analog input
int average = 0; // the average
int inputPin = A0;
void setup()
{
// initialize serial communication with computer:
Serial.begin(9600);
// initialize all the readings to 0:
for (int thisReading = 0; thisReading < numReadings; thisReading++)
readings[thisReading] = 0;
}
void loop() {
average = potAverage(inputPin , readings[numReadings], numReadings);
Serial.println(average);
delay(1); // delay in between reads for stability
}
int potAverage(int potPin, int readings[], int numReadings){
int index = 0;
int value = analogRead(potPin);
// subtract the last reading:
int total = total - readings[index];
// read from the sensor:
readings[index] = value;
// add the reading to the total:
total = total + readings[index];
// advance to the next position in the array:
index = index + 1;
// if we're at the end of the array...
if (index >= numReadings){
// ...wrap around to the beginning:
index = 0;
}
// calculate the average:
int average = total / numReadings;
return average;
}