Press Button to Play Random Tone
Step 1 - Build the Project
For this project, you combine an input, an output, and a built-in function of the Arduino code: random(). C++ also has a rand() function, but Arduino’s is a little easier to use.
Step 2 - Upload the Code
Step 3 - Read the Walkthrough
After setting up the button pin as an INPUT_PULLUP and the speaker as an OUTPUT, it’s up to the software to decide what tone you’ll get when the button is pressed. The input is tied directly to the output, so the ‘if’ loop is checking the status of the button constantly to see if it is pressed. If it is, a random tone between 100 and 1100 is generated and inserted into the tone() function of Arduino.
The delay in the code keeps the loop from running as fast as it possibly can. If it did, then the tone would be changing multiple times per second. For a strobing effect, you can hold down the button and change the delay between button checks.