Download What`s a Microcontroller Text

Transcript
Chapter #8: Frequency and Sound · Page 243
Depending on the octave, we want to divide noteFreq by either 1, 2, 4, or 8. That means
that the goal is really to divide by 20 = 1, 21 = 2, 22 = 4, or 23 = 8. The statement below
takes the value of noteOctave, which could be a value between 5 and 8, and subtracts
that value from 8. If noteOctave was 8, now it’s 0. If noteOctave was 7, now it’s 1.
If noteOctave was 6, now it’s 2, and if noteOctave was 5, now it’s 3.
noteOctave = 8 - noteOctave
Now, noteOctave is a value that can be used as an exponent of 2, but how do you raise 2
to a power in PBASIC? One answer is to use the DCD operator. DCD 0 is 1, DCD 1 is 2,
DCD 2 is 4, and DCD 3 is 8. Dividing noteFreq by DCD noteOctave means you are
dividing by 1, 2, 4, or 8, which divides noteFreq down by the correct value. The end
result is that noteFreq is set to the correct octave. You will use the Debug Terminal in
the Your Turn section to take a closer look at how this works.
noteFreq = noteFreq / (DCD noteOctave)
How am I supposed to know to use the DCD operator? Keep learning and practicing.
Every time you see a new command, operator, or any other keyword used in an example,
look it up in the BASIC Stamp manual. Read about it, and try using it in a program of your
own design. Get in the habit of periodically reading the BASIC Stamp Manual and trying the
short example programs. That’s the best way to get familiar with the various commands and
operators and how they work. By doing these things, you will develop a habit of always
adding to the list of programming tools you can use to solve problems.
The first two lines of code for determining the note duration are about the same as the
code from the previous example program. Now, however, any note could be dotted,
which means the duration might have to be multiplied by 1.5. A READ command is used
to access values stored in EEPROM by the Dots DATA directive. An IF…THEN statement is
used to multiply by 3 and divide by 2 whenever the value of the noteDot variable is 1.
READ Durations + index, noteDuration
noteDuration = WholeNote / noteDuration
READ Dots + index, noteDot
IF noteDot = 1 THEN noteDuration = noteDuration * 3 / 2