This application note will demonstrate a few examples that generate sound with the Cubloc. Sound can be generated using the Cubloc's I/O port or PWM channel. With a PWM channel, sounds of varying frequency can be generated.
Const Device = CB220 Dim PLAYSTR As String Low 5 Freqout 0,5236 'Create a sound with frequency of 440Hz Delay 500 'Delay Pwmoff 0 'Stop Sound by turning off PWM
The example above shows the CB220's PWM channel 0 of CB220 being used with the FreqOut command to produce a sound.
With commands like FreqOut and Delay, simple sounds can be created.
Const Device = CB220 Low 5 FreqOut 0,4403 Delay 200 FreqOut 0,3703 Delay 200 FreqOut 0,3114 Delay 200 FreqOut 0,2202 Delay 200 PwmOff 0
By changing the frequencies, a simple program can be made that plays musical notes.
|Octave 4||Octave 5|
To express one note, 2 characters are used: the first character is for the frequency of the note and second character is for the length of the note.
Const Device = CB220 Dim PLAYSTR As String Low 5 PLAYSTR = "G5E3E3G3E3C5" PLAY 0,PLAYSTR Do Loop End Sub PLAY(CH As Byte,NOTE As String) Dim PL As Byte Dim CHAR As Byte Const Integer PLAYTABLE = (5236,4665,4403,3923,3495,3299,2939,2618,2333,2202,1961,1747,1649,1469,0) For PL=1 To Len(NOTE) Step 2 CHAR = Asc(Mid(NOTE,PL,1)) - &H41 FreqOut CH,PLAYTABLE(CHAR) CHAR = Asc(Mid(NOTE,PL+1,1)) - &H30 Delay CHAR*100 Next PwmOff CH End Sub
When using the PWM port for other purposes, the FreqOut command cannot be used. To get around this limitation, any regular I/O port can be used to create sound. The following example shows how to make an alert sound with I/O port P4. This program uses the Reverse and UDelay commands to alternate the I/O port between logic-high and logic-low
Const Device = CB220 Low 4 Do SOUND 4,110,60 SOUND 4,80,60 SOUND 4,40,160 Loop End Sub SOUND(PN As Byte,FR As Byte,LN As Byte) Dim SI As Byte,SJ As Byte For SJ = 0 To LN Reverse PN UDelay FR Reverse PN UDelay FR Next End Sub