// Define the speaker pin
#define SPEAKER_PIN 8
// Define arrays for button pins and corresponding tones
const int buttonPins[] = { 12, 11, 10, 9, 7, 6, 5 };
// Change the numbers in the array above to the pins you are using
// These are the pins being used for this tutorial
const int buttonTones[] = {
261.626, 293.665, 329.628, 349.228, 391.995, 440, 493.883
};
const int numTones = sizeof(buttonPins) / sizeof(buttonPins[0]);
void setup() {
// Set up button pins as INPUT_PULLUP (with internal pull-up resistors)
for (int i = 0; i < numTones; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
}
// Set the speaker pin as OUTPUT
pinMode(SPEAKER_PIN, OUTPUT);
}
void loop() {
int pitch = 0;
// Iterate through the button pins to check if any buttons are pressed
for (int i = 0; i < numTones; i++) {
if (digitalRead(buttonPins[i]) == LOW) { // If a button is pressed (LOW state)
pitch += buttonTones[i]; // Add the corresponding tone to the pitch
}
}
if (pitch) {
// If pitch is not zero, play the tone on the speaker
tone(SPEAKER_PIN, pitch);
} else {
// If no button is pressed, stop playing the tone
noTone(SPEAKER_PIN);
}
}