// Copyright 2007, Sandeep Gangadharan // For more free scripts go to http://www.sivamdesign.com/scripts/

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 of that statement. 

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); } } // (c) 2017 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

Challenges

How many can you complete? Change the code and hardware according to the challenges below. Upload your code to see the effect when you're finished. Complete a challenge? Check it off the list!

Videos

Read the Code Walkthrough Text (click to open)

Concepts

New Concept: Multiple Inputs

You can think about the components you're using in a program as building blocks. They have different abilities, but you can combine them with code to create something unique. 

Using multiple inputs of the same type, like four buttons, is simple as long as you keep track of each component. All of the same functions, like digitalRead() or digitalWrite() will work with multiple components in the same program. 


Quiz

If you're having trouble, try to run a program that can help you find the answer.

1. How many arguments does the digitalRead() function require?



2. In Four Note Piano, what happens if you press button 4 and button 12 at the same time?