Press Button to Play a Tone
 

Step 1 - Build the Project

This code ties an input (the button) directly to an output (the speaker) with an if-else statement. Pay close attention to the way the if-else statement uses parentheses and braces- you'll see this structure in many programs.

Step 2 - Upload the Code

/* * This program plays a tone on a speaker attached to pin 2 * when a button attached to pin A5 is pressed. */ void setup(){ pinMode(A5, OUTPUT); //speaker pin pinMode(12,INPUT_PULLUP); //pushbutton } void loop(){ //If the button is pressed, play a tone of 450 hertz if (digitalRead(12) == LOW){ tone(A5,450); } else {noTone(A5);} } // Use delay and tone to play a few notes when the button is pressed // (c) 2017 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

Step 3 - Read the Walkthrough

First, you set up the components. Since we’re reading the status of the button, we make that the INPUT_PULLUP. The speaker is set as an OUTPUT so it’s ready to receive power.

The loop is designed to constantly check the status of the button and, if it is pressed, turn on the speaker at a tone of 450 hertz. Otherwise, the speaker should stay off if the button isn’t pressed. Although this code doesn’t look like much, the loop is checking the button’s status hundreds of times per minute!