Basic Blaster Sound Effects

Even in deep space, lasers should have a cool sound effect. Learn how to add one to your laser blaster LEDs that are triggered with a button press.

Code

The code in the editor below already works Just plug in your Code Rocket and press upload to see what it does! Tinker with it and make changes to see what each line of code controls.

/* Light up the Blaster LEDs and play a sound when the corresponding button is pressed */ void setup(){ pinMode(2,OUTPUT); //Speaker pinMode(7,OUTPUT); //Blaster LED pinMode(8,OUTPUT); //Blaster LED pinMode(12,INPUT_PULLUP); //Button pinMode(11,INPUT_PULLUP); //Button } void loop(){ if(digitalRead(12)==LOW){ //if button 12 is pressed digitalWrite(8,HIGH); //turn on LED 8 tone(2,500); //play a tone of 500 hertz on on the speaker } else if(digitalRead(11)==LOW){ //if button 11 is pressed digitalWrite(7,HIGH); //turn on LED 7 tone(2,800); //play a tone of 800 hertz on the speaker } else{ //if neither button 11 or 12 is pushed, turn off both lights and the speaker digitalWrite(7,LOW); digitalWrite(8,LOW); noTone(2); } } // (c) 2018 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

Walkthrough Videos

Watch the videos for line-by-line explanation of how the example program works. Then you'll be ready to make some changes of your own!

Challenges

Can you complete the challenges? Change the code in the editor above, then upload it to your Code Rocket and see if you got the result. Don't stop here, keep experimenting with the code!

Concepts

These are the new code concepts covered in this example program. To become a great coder, read through these concepts to learn new vocabulary.

New Concept: If - Else If - Else

The sequence of statements ‘if’, followed by ‘else if’, followed by ‘else’ creates a priority in the program around which condition is checked first. This concept is useful when you want only one of the possible conditions from your statements to be true. In this case, you want either laser blaster 7 to be on and play its tone, or you want laser blaster 8 to be on and play its tone, or you want neither to be on and no tone to play. There are three scenarios that could happen each time the void loop of the code runs, but you want the program to only be able to pick one of those scenarios.

When you’re designing a program like the one in this example, you need to consider which condition should have ‘priority’ over the others and put that condition in the ‘if’ statement, leaving the other conditions to the ‘else if’ statements that follow after it.

Quiz

If you're having trouble, try to run an experimental program or look at the example code to help you find the answer.

1. True or False: You can have an 'else-if' statement without an 'if' statement.



2. True or False: The 'else' statement runs only if the conditions of the 'if' and 'else-if' statements are not true.