Four Note Piano with Synced LED

For this piece of code, you combine 4 inputs and 2 outputs. Each input will affect both outputs- each button press creates a tone and turns on a light. You’re adding together many simple parts to create a more complex and interesting project!

Code

/* * Play a tone on a speaker attached to pin A5 and light an LED on * pin 2 when buttons attached to pins 4,6,9,12 are pressed. */ void setup() { pinMode(A5, OUTPUT); //speaker pinMode(2, OUTPUT); //set the LED as an OUTPUT //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 tone (in hertz) and light up the LED. if (digitalRead(4) == LOW) { tone(A5, 250); digitalWrite(2, HIGH); } else if (digitalRead(6) == LOW) { tone(A5, 350); digitalWrite(2, HIGH); } else if (digitalRead(9) == LOW) { tone(A5, 450); digitalWrite(2, HIGH); } else if (digitalRead(12) == LOW) { tone(A5, 550); digitalWrite(2, HIGH); } else { noTone(A5); digitalWrite(2, LOW); } } // (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: Code Combinations

Combining past projects of your own, or using other people's code with your own new ideas, is very common and a great way to speed up your projects and get help from others. Learning to combine code correctly is a skill in itself. 

You need to think carefully about how the new commands may interact with existing code. For example, say you want to combine a program that flashes a light for a second with a program that beeps a speaker on and off once a second. If you copy every single line from one program to another, you'll end up with two delays in your program- not what you intended. 

When you want to combine two pieces of code, especially when there is complicated syntax, try to break down the code into smaller chunks in your mind, recognizing what each line is meant to do by itself. 

Quiz

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

1. How many code commands can be run inside an 'if' statement?




2. When you type the code:
tone(A5, 250);
digitalWrite(2, HIGH);

which command runs first?




3. When does an 'else' statement run?