Go Down

Topic: How do I use a button to make sound? (conductive paint is involved) (Read 546 times) previous topic - next topic

Mossi

I'm new to Arduino and am doing a project with conductive paint. I have it all set up so that there is a space that doesn't complete the circuit (I have been told this will work as a pushbutton). There is a separate piece of paper covered with the conductive paint and when you put it down it should complete the circuit and make noise. At the moment it makes noise on a loop anyway. Below is the code for the sound but I think I need to add a button in there so it will work. I used the button example and it uploaded with the code underneath but the music still looped...

Code: [Select]
// Project 11 - Melody Player
int speakerPin = 9;
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() {
  pinMode(speakerPin, OUTPUT);
}

void loop() {
  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);
  }
}

Grumpy_Mike

Look at your code in the post, it is mangled.

Modify the post. Delete the code. Paste it in again and select it all. Then hit the #icon and save.
This will put the code in a box so others can copy and compile it and see if they can help.

Mossi


Grumpy_Mike

Quote
I used the button example and it uploaded with the code underneath

What do you mean by this?
There is no button code in the sketch you posted.
There is no underneath to put anything. When you upload a sketch it completely replaces what is there already.

You need to incorporate the "button"  in your loop. After setting up the button pin number in a variable called 'pin' then your loop would look something like this:-
Code: [Select]
void loop() {
if(digitalRead(pin) == LOW) {  // make the sound if you read LOW from the button.
  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);
  }
}
}

Go Up