Here's my problem. At the moment when I press down a piece of conductive painted card onto the painted circuit to close the circuit, a song stops playing, however I want it so that there is no sound, then you press the conductive painted card down to complete the circuit and sound starts?
(I am new to Arduino and code!)
// Project 11 - Melody Player
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 9; // the number of the pushbutton pin
const int speakerPin = 9; // the number of the speaker pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int length = 15; // the number of notes
char notes[] = "ccggaagffeeddc "; // a space represents a rest
int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };
int tempo = 300;
void playTone(int tone, int duration) {
for (long i = 0; i < duration * 1000L; i += tone * 2) {
digitalWrite(speakerPin, HIGH);
delayMicroseconds(tone);
digitalWrite(speakerPin, LOW);
delayMicroseconds(tone);
}
}
void playNote(char note, int duration) {
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };
// play the tone corresponding to the note name for (int i = 0; i < 8; i++) {
for (int i = 0; i < 8; i++) {
if (names[i] == note) {
playTone(tones[i], duration);
}
}
}
void setup() {
// initialize the speaker pin as an output:
pinMode(speakerPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
pinMode(speakerPin, OUTPUT);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn speaker on:
digitalWrite(speakerPin, HIGH);
}
else {
// turn speaker off:
digitalWrite(speakerPin, LOW);
}
for (int i = 0; i < length; i++) {
if (notes[i] == ' ') {
delay(beats[i] * tempo); // rest
} else {
playNote(notes[i], beats[i] * tempo);
}
// pause between notes
delay(tempo / 2);
}
}