Search code examples
arduinoledqpushbuttonspeaker

How can I combine an LED and a piezzo with a push button on arduino?


I would like to know how i can combine in one code my LED and piezzo buzzer. I want to stop the music as soon as I push the push button, and to turn on a light(LED) at the same moment. My code is not working, could you pleasy tell what I should do?

      int buttonState = 0;
      int speakerPin = 10;
      int buttonPin= 7;
      int frequency = 500;
      int ledPin = 13;
      int length = 17; // the number of notes
      char notes[] = "gcefgcefgcefgcefga "; // a space represents a rest
      int beats[] = {2,2,1,1,2,2,1,1,2,2,1,1,2,2,1,1};
      int tempo = 250;

      void setup() {            
        pinMode(speakerPin, OUTPUT);
        pinMode(ledPin, OUTPUT);
        pinMode(buttonPin,INPUT);
      }

      void loop() {
        buttonState = digitalRead(buttonPin);

        if (buttonState==HIGH){
          digitalWrite(ledPin, HIGH);
          noTone(speakerPin);
        }else {
          char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
          char notes[] = "gcefgcefgcefgcefga ";         
          digitalWrite(ledPin, LOW);
          digitalWrite(speakerPin,HIGH);
          if (long i = 0; i < duration * 5000L; i += tone * 15) {

          }

      void playTone(int tone, int duration) {

          for (long i = 0; i < duration * 5000L; i += tone * 15) {
          if (buttonState==LOW){
          digitalWrite(speakerPin, HIGH);
          delayMicroseconds(tone);
          digitalWrite(speakerPin, LOW);
          delayMicroseconds(tone);
          } 
        }
      }

      }} 

Solution

  • there could be a few different reasons as to why your code isn't working. For starters: you haven't defined noTone and I don't see playTone actually being used, but at a high level what you're trying to do is quite simple and this pseudocode should help:

     void loop() {
        buttonState = digitalRead(buttonPin);
        if buttonState==LOW
    
        playTone();
        digitalWrite(ledPin, LOW);
        else {break out of loop}
        //add in your pause here
        delayMicroseconds(pause);//I'm not sure why you put tone here in your code, just initialize int of 1000 or something  
    
    }
    

    you got this! hope this helps!