const int numReadings = 10;
int readings[numReadings]; // the readings from the analog input
int index = 0; // the index of the current reading
int total = 0; // the running total
int average = 0;
int micPin = A0;
int ledPin = 6;
void setup() {
// put your setup code here, to run once:
// initialize serial communication with computer:
pinMode(micPin, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
Serial.begin(9600);
// initialize all the readings to 0:
for (int thisReading = 0; thisReading < numReadings; thisReading++)
readings[thisReading] = 0;
}
void loop() {
// put your main code here, to run repeatedly:
// subtract the last reading:
total= total - readings[index];
// read from the sensor:
readings[index] = analogRead(micPin);
// 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:
average = total / numReadings;
// send it to the computer as ASCII digits
Serial.println(average);
delay(1); // delay in between reads for stability
int newAvg = map(average, 0, 1023, 0, 255);
analogWrite(ledPin, newAvg);
}
Click to Expand
Content Rating
Is this a good/useful/informative piece of content to include in the project? Have your say!
You must login before you can post a comment. .