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

/* * Play a random tone on a speaker attached to pin A5 * when a button attached to pin 12 is pressed. */ void setup(){ pinMode(A5, OUTPUT); //speaker pin pinMode(12,INPUT_PULLUP); //pushbutton } void loop(){ //If the button is pressed, play a random tone between 100 and 1100 if (digitalRead(12) == LOW){ tone(A5,random(100,1101)); delay(300); } else { noTone(A5); } } // Change the only delay for some wild effects when the button is held // (c) 2017 Let's Start Coding. License:

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.