Step 4 - Watch the Video Walkthrough

Code Walkthrough Text

This program uses the speed of the Maker Board to make tiny changes to a pitch very quickly, giving it a smooth sound. This is also a place that illustrates the power of variables- you won't always be able to tell what the exact value of the tone is, but the variable pitch holds that value for you in the program.

The first line of the program creates the pitch variable and gives it a value of 40. The speaker makes some strange sounds below 40 hz and, with the variable, you can start the pitch wherever you'd like.

In the void setup(), you need to tell Maker Board how to set up each pin you'll use.

The void loop() starts by playing the tone 'pitch' on pin A5. Because you haven't done anything to change pitch, it will be 40, as it was when you declared it. The very short delay is what allows your program to change tone quickly and smoothly, but not sound garbled. Change it or delete it to see what happens to the code.

Next, an if statement checks the button on pin 12. If it is pressed, the pitch variable is increased by 1. In our example, pitch is now 41. The else statement is skipped (because the if is true). The second if condition is evaluated, then skipped because it is false.

Once the loop is complete, it repeats. Now that pitch equals 41, the tone played at the top of the loop will be 41.

Now assume that you've released the button after holding it down for only one loop (this would be really difficult because of the speed of the program). Now, the if(digitalRead(.... statement is false, so the else statement will run. It reassigns pitch to be one less than it was before- back to 40.

The second if statement will now be true, setting pitch to 40 (again). Think about the purpose of this second if statement. Imagine that you release the button as soon as you start this program. The variable pitch will quickly become 39, 38, 37, and so on down to 0. What happens at 0? The pitch continues to decrease. You won't hear anything, but pitch will silently decrease to -99, -100, -101 and so on into the thousands.

Now when you press the button again, pitch will increase, but if it started at -100, it will take 100 loops of the void loop before pitch is equal to 0.

This second if statement ensures that never happens.

The short delay is what allows this program to sound smooth- it allows the variable to quickly change and do in only a few lines what it would take hundreds of lines to do with tone, delay, tone, delay....