Press Button to Stop a Tone
 

Step 1 - Build the Project

This code ties the INPUT_PULLUP button directly to the OUTPUT of the speaker. The hardware is exactly the same as a button playing a tone, but here you use the code to change the ‘default’ condition. Instead of being silent until the button is pressed, the speaker will play until you make it stop with a button press!

Step 2 - Upload the Code

/* * Play a tone on a speaker attached to pin A5 UNLESS a button * attached to pin 12 is pressed. */ void setup(){ pinMode(A5, OUTPUT); //speaker pinMode(12, INPUT_PULLUP); //pushbutton } void loop(){ //If the button is pressed, stop a 450 hertz tone on pin A5 if (digitalRead(12) == LOW){ noTone(A5); } else {tone(A5,450);} //otherwise, leave the speaker on at 450 hertz } // Add delay and noTone to the 'else' statement so the tone beeps on and off // (c) 2017 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

Step 3 - Read the Walkthrough

 

After setting up the hardware components, you’ll use an ‘if’ loop to check the status of the button over and over again. First, you write the default condition: the speaker is playing the tone of 450 hertz. Then, you build the test with an ‘if’ loop. The loop runs hundreds of times per minute, checking the status of the ‘if’ loop. If the condition is true (the button is pushed), the code within the ‘if’ loop runs and the tone is stopped.