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
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!