My code should be designed to play music when a light switch is flicked, but plays a continuous sound instead. How can I fix this?
// set pin numbers:
const int buttonPin1 = 13;
const int buttonPin2 = 12;
const int buttonPin3 = 8;
const int buttonPin4 = 7;
const int buttonPin5 = 4;
const int buttonPin6 = 2;
const int Speaker1 = 11;
/* Play Melody
-
-
Program to play a simple melody
-
Tones are created by quickly pulsing a speaker on and off
-
using PWM, to create signature frequencies.
-
Each note has a frequency, created by varying the period of
-
vibration, measured in microseconds. We'll use pulse-width
-
modulation (PWM) to create that vibration.
-
We calculate the pulse-width to be half the period; we pulse
-
the speaker HIGH for 'pulse-width' microseconds, then LOW
-
for 'pulse-width' microseconds.
-
This pulsing creates a vibration of the desired frequency.
*/
// Tones
// define note, period & frequency
#define c 3830 // 261 Hz
#define d 3400 // 294 Hz
#define e 3038 // 329 Hz
#define f 2864 // 349 Hz
#define g 2550 // 392 Hz
#define a 2272 // 440 Hz
#define b 2028 // 493 Hz
#define c 1912 // 523 Hz
#define R 0 // rest
// Start Program
void setup() {
pinMode(buttonPin1, INPUT);
pinMode(buttonPin2, INPUT);
pinMode(buttonPin3, INPUT);
pinMode(buttonPin4, INPUT);
pinMode(buttonPin5, INPUT);
pinMode(buttonPin6, INPUT);
pinMode(Speaker1, OUTPUT);
Serial.begin(9600);
}
void loop() {
byte buttonState1 = digitalRead(buttonPin1);
byte buttonState2 = digitalRead(buttonPin2);
byte buttonState3 = digitalRead(buttonPin3);
byte buttonState4 = digitalRead(buttonPin4);
byte buttonState5 = digitalRead(buttonPin5);
byte buttonState6 = digitalRead(buttonPin6);
// when buttonPin is pushed, it's HIGH
// when buttonPin is not pushed, it's LOW
if (buttonState1 == HIGH) {
tone(Speaker1, d, d);
delay (500);
tone(Speaker1, d, d);
noTone(13);
}
if (buttonState2 == HIGH) {
tone(Speaker1, d, d);
delay (500);
tone(Speaker1, d, d);
noTone(12);
}
if (buttonState3 == HIGH) {
tone(Speaker1, c, a);
delay (500);
tone(Speaker1, c, a);
noTone(18);
}
if (buttonState4 == HIGH) {
tone(Speaker1, c, a);
delay (500);
tone(Speaker1, c, a);
noTone(7);
}
if (buttonState5 == HIGH) {
tone(Speaker1, b, d);
delay (500);
tone(Speaker1, b, d);
noTone(4);
}
if (buttonState6 == HIGH) {
tone(Speaker1, b, d);
delay (500);
tone(Speaker1, b, d);
noTone(2);
}
}