3_9_1 Bug Hunt: Four Note Piano

Bug Hunt! Test your Troubleshooting.

Prefer listening over reading? Click the play button in the audio bar.

Here’s how Bug Hunts work:

We’ve taken the example code from the last project and inserted errors into it. These errors might be spelling problems, syntax, or we might have changed up how the program works altogether!

The goal of the Bug Hunt is to find and fix the errors so that when you upload the code, it runs just like the example code did on the project page.

Try these steps in order to solve a Bug Hunt:

1) Look over the code closely first, looking for anything that is out of place. We recommend you do this first to build up your ‘bug hunting instincts’.

2) Press ‘Upload the Code’ with your board plugged in and the circuit built. The code won’t work, but it will show you the errors that the computer found - these will pop up in a box just below the code editor. These clues are sometimes vague or confusing, but they may help you find out where the problem is.

3) Check your code references, especially for the functions that have turned red when you hit “Upload”. Compare the syntax of your reference book to the syntax in your code editor here.

After you’ve fixed the bug and the code is working again, hit ‘Restore’ so you can see the code how it was before you fixed it. Is the bug obvious to you now? Reviewing like this will make it easier to find bugs in future programs!

Get stuck? Click on ‘Need a Hint?’ below. It will provide a clue about what’s wrong in this program.

/* Create a 4 note piano where each of the 4 buttons plays a different tone */ void setup(){ pinMode(4,INPUT_PULLUP);//button pinMode(5,INPUT_PULLUP);//button pinMode(6,INPUT_PULLUP);//button pinMode(7,INPUT_PULLUP);//button pinMode(2,OUTPUT); //speaker } void loop(){ if(digitalRead(4)==LOW){ //if button 4 is pressed tone(2,500); //play a tone of 500 hertz on the speaker } else{ //otherwise if none of the if-else if statements are true noTone(2); //stop any tones playing on the speaker } else if(digitalRead(5)==LOW){ //otherwise if button 5 is pressed tone(2,700); //play a tone of 700 hertz } else if(digitalRead(6)==LOW){ //otherwise if button 6 is pressed tone(2,900); //play a tone of 900 hertz } else if(digitalRead(7)==LOW){ //otherwise if button 7 is pressed tone(2,1100); //play a tone of 1100 hertz } } // (c) 2023 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 



When you have lots of if-else if-else statements in your code, it's important to keep them straight, because the code checks each condition from top to bottom. The 'else' statement comes last and that's the code that runs if none of the 'if' or 'else if' conditions are true.

If the if-else if-else statements got out of order, the program might not be able to check all of the conditions in the code! Make sure the 'else' statement is in the right place.