Ascend to Charge Part Four: Double Speed

Automatically speed up your song each time it plays through using a speed variable. Pretty soon, it will play too fast to hear anything more than a ‘blip’!

Code

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

//'Ascend to Charge', a popular song during baseball games // In this version, the song speeds up by double each time it plays int C = 523; int E = 659; int G = 784; int A = 880; //C,E,G,A,E,G is the sequence of notes for this song int note = 150; //how long each note plays void setup(){ pinMode(10,OUTPUT); //Set the Speaker as an OUTPUT } void loop(){ tone(10,C); delay(note); tone(10,E); delay(note); tone(10,G); delay(note); tone(10,A); delay(note*2); //This note is held for twice the value of the variable tone(10,E); delay(note); tone(10,G); delay(note*4); //Hold the end note for four times the value of the variable. noTone(10); delay(3000); //wait 3 seconds before replaying the song note = note/2; //each time the loop runs, the value of 'note' is cut in half } // (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 challenge? Change the code in your code editor above. Upload your code to see the effect when you're finished. Complete a challenge? Check it off the list!


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: Changing variable values

Up until now, variables have been a replacement for numbers in your program. In this project, you see a new way to use variables as values that change over time! When you use variables this way, your code is updating itself. This is a big advantage of using variables. As a programmer, you can build the ‘system’ and put the rules in place, then the code can run and change itself!

Note on integers: You may remember from previous lessons and videos that the integer (int) type variable can only be a whole number. As the note variable divides by 2 each time, it will eventually include some decimals, like the number 37.5. Because we used an integer variable, the program will ignore that decimal and instead see the number as 37.

Eventually, the variable will be so small that dividing it by 2 again makes the variable have a value less than 0. An integer variable will ignore the decimal, so the variable will get ‘stuck’ at 0 and can’t be divided anymore.

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. What will the 'note' variable equal the second time the void loop runs?