int buttonState = 0; // variable for reading the pushbutton status
const int numReadings = 10; //average 10 values
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; // the average
int inputPin = A6;
void setup() {
// initialize serial communications (for debugging only):
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
// initialize all the readings to 0:
for (int thisReading = 0; thisReading < numReadings; thisReading++)
readings[thisReading] = 0;
}
void loop() {
//read the button and store it’s state in new variable
buttonState = digitalRead(buttonPin);
// subtract the last reading:
total= total – readings[index];
// read from the sensor:
readings[index] = analogRead(inputPin);
// 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);
// map the pitch to the range of the analog input.
// change the minimum and maximum input numbers below
// depending on the range your sensor’s giving:
int thisPitch = map(average, 30, 0, 100, 1000);
// if button in pressed do this…
if (buttonState == LOW){
// play the pitch:
tone(7, thisPitch, 10);
delay(1); // delay in between reads for stability
}
}
[/code]