There are lots of options for writing simple "synth" programs using MakeCode! Here's an example that uses the
on tilt Input blocks. When you tilt the CPX, it triggers an event that plays notes which go up or down, faster or slower. The button below will open the program in MakeCode so you can test it and play around with it. Then read the instructions to see how it was put together.
When you control musical sounds with movement, you are changing the numbers that represent those sounds: the pitch, the tempo, the duration, and the volume. To change the pitch, you need to replace the names of the notes with their numbers.
As you already saw, every note on the drop-down piano keyboard on a
play tone shows a number when you press it. This is the frequency of that note. It measures how often a sound wave at that pitch vibrates in one second, and is given in hertz (written Hz).
Middle C has a frequency of 262 Hz. Middle A, five notes higher on the piano keyboard, has a frequency of 440. By using numbers instead of names, the CPX can play a much wider range of frequencies than the keys on the piano keyboard, including tones between standard notes.
Changing Pitch Using Variables
MakeCode includes a
But to do the same with the pitch, you need a couple extra steps. First, you'll replace the number with a variable. Then you can change the variable to change the number.
Create a Variable for the Pitch
Click on the VARIABLES category to open up a box that lets you give the variable a name. Let's call this "Note."
The VARIABLES menu now contains blocks with the name Note.
To set the value of Note when you begin the program, take an
Type in whatever frequency you like. In this example, Note starts out as
Use the Tilt Blocks to Create Notes
Go to the INPUT Menu and drag an
Test the code on the simulator. Every time you tilt the board to the left, it should play a note that's a little higher than the last one. (The notes may sound sharp or flat because they are not exactly 30 Hz apart.)
To play a string of notes going up, grab a
It's handy to add some lights to show which way the board is tilted. From the LIGHT menu, add a
At the very end of the stack, add a
Add Code for Tilt Right, Up, and Down
Right click on the top of the
Then replace the number in the
Add INPUT blocks for tilt down and tilt up the same way, but instead of changing the pitch, use the