Four Note Piano
 

Step 1 - Build the Project

This code combines 4 button inputs to vary the output of a speaker. Each input is assigned a different output tone using if-else if statements. Once each button is set up to receive input and the speaker is set as an OUTPUT, the loop checks the status of each button until it finds one that is pulled LOW by a press. Then, it runs the code between the { and }.

Step 2 - Upload the Code

/* * Play a tone on a speaker attached to pin A5 when * buttons attached to pins 4,6,9,12 are pressed. */ void setup(){ pinMode(A5, OUTPUT); //speaker pin //initialize the buttons as inputs: pinMode(4,INPUT_PULLUP); pinMode(6,INPUT_PULLUP); pinMode(9,INPUT_PULLUP); pinMode(12,INPUT_PULLUP); } void loop(){ //if a button is pressed, play the corresponding tone (in hertz) if (digitalRead(4) == LOW) { tone(A5,250); } else if (digitalRead(6) == LOW) { tone(A5,350); } else if (digitalRead(9) == LOW) { tone(A5,450); } else if (digitalRead(12) == LOW) { tone(A5,550); } else{ noTone(A5); } } // Replace the tone value 250 with a variable you create. Then make each // higher note have a tone of: yourToneVariable + a number // (c) 2017 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

Step 3 - Read the Walkthrough

The if- else if structure allows the loop to stop checking the remaining else-if statements after any of them is proven true. For example, if digitalRead(4) == LOW, the code won’t go on to check if digitalRead(6) == LOW. This allows you to create a priority of your ‘if’ statements. If you press two buttons at once, the one higher in the else-if will run and nothing below it will run.

Here, even the ‘else’ noTone() won’t run immediately after a button is released. Instead, the code will start back from the top and check each button again and only run the noTone() function when there are no buttons pressed that time. Remember, all of this is happening so fast that it’s hard to notice any difference!