0

My ciruit: enter image description here

My code:

// Pin 13 has a LED connected on most Arduino boards.
// give it a name:
int led = 13;
const int buttonPin = 2;


// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

// the loop routine runs over and over again forever:
void loop() 
{
  bool buttonState = digitalRead(buttonPin);
  while (buttonState == LOW)
  {
   digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
   delay(1000);               // wait for a second
   digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
   delay(1000);               // wait for a second
   tone(12,260);
  {
 }
  }
}

What I wish to do, is that when the button is pressed, and the Led's start to blink, I want the piezo buzzer to make a sound. I have never worked with them before so I am having troubles getting results. Is it that the setup is wrong or the code needs extra lines than just the tone(12,260); that I added?

Utsav
  • 231
  • 2
  • 9
  • 17

1 Answers1

2

Both the code and the circuit have problems.

In the code:

• If the while (buttonState == LOW) loop is ever entered, it will never be left, because buttonState, the controlling variable, does not change within the loop.

The simplest fix is to remove the line bool buttonState = digitalRead(buttonPin); and replace while (buttonState == LOW) with while (!digitalRead(buttonPin)), which says to loop while digitalRead(buttonPin) is not true; ie, while it is false, or low.

• The empty braces, { } at the end of the while loop are superfluous and should be deleted.

In the circuit diagram:

• Neither of the leads of the buzzer is attached to the Arduino circuit, so it won't make any sound. Note, tone(12,260); tells the Arduino to use pin 12 for tone output.

To fix this problem, run a wire from pin 12 to one side of the buzzer, and a wire to ground for the other side of the buzzer.

• A blue LED in series with a red LED might or might not turn on when supplied with 5 V. For example, if the red LED takes 1.8 V and the blue LED takes 3.3 V to turn on, the 5.1 V total is too high to be turned on by 5 V signals. Remove one of the two LEDs, and move the wires to the other LED to complete a circuit.

James Waldby - jwpat7
  • 8,920
  • 3
  • 21
  • 33