' Make it with Micromite
' Part 7: Adding sound to a projet
'
' Listing 3: Code to play multiple musical tunes
 

'setup
SETPIN 22,DOUT                     ' set 0v supply to piezo
CONST C4=262,D4=294,E4=330,F4=349,G4=392,A4=440,B4=494
CONST C5=523,D5=587,E5=659,F5=698,G5=784,A5=880,B5=988
CONST pp=0                         ' represents a silent note
Tempo=1.0                          ' increase to speed up, decrease to slow down

' Tune DATA 
  ' Two pieces of data per note, the note name and note duration: Note, Duration
  ' For Duration: 1=whole note, 2=half note, 4=quarter note, 8=eighth...
Tune1:
  Data C4,2, C4,2, G4,2, G4,2, A4,2, A4,2, G4,1
  Data F4,2, F4,2, E4,2, E4,2, D4,2, D4,2, C4,1
  Data G4,2, G4,2, F4,2, F4,2, E4,2, E4,2, D4,1
  Data G4,2, G4,2, F4,2, F4,2, E4,2, E4,2, D4,1
  Data C4,2, C4,2, G4,2, G4,2, A4,2, A4,2, G4,1
  Data F4,2, F4,2, E4,2, E4,2, D4,2, D4,2, C4,1, pp,999  ' end-of-tune marker (i.e. Duration=999)
  
Tune2:
  Data G4,4, G4,4, A4,2, G4,2, C5,2, B4,1, pp,32
  Data G4,4, G4,4, A4,2, G4,2, D5,2, C5,1, pp,32
  Data G4,4, G4,4, G5,2, E5,2, C5,2, B4,2, A4,1, pp,16
  Data F5,4, F5,4, E5,2, C5,2, D5,2, C5,1, pp,999

' main program
DO
  RESTORE Tune1                    ' point MMBASIC to Tune1 DATA
    PlayTune                       ' call SUB to play the tune contained in the DATA
    PAUSE 1000                     ' have a gap before next tune
  RESTORE Tune2                    ' point to Tune2
    PlayTune                       ' play the tune
    PAUSE 1000                     ' and another gap before next tune
LOOP                               ' continually play the two tunes....

' subroutines
SUB PlayTune                       ' play tune DATA (up to end-of-tune marker)
  DO
    READ Note,Duration             ' read two bits of note-data, load into variables: Note and Duration
    IF Duration=999 THEN EXIT DO   ' check to see if 'end-of-tune' marker. If so then exit DO/LOOP
    IF Note>20 THEN PWM 2,Note,50  ' check if a note. If so, set PWM pin 26 at frequency in Note
    PAUSE 1000/(Duration*Tempo)    ' leave note playing for required time
    PWM 2,STOP                     ' now stop the PWM output
    PAUSE 10/Tempo                 ' add a small pause before next note
  LOOP                             ' continue with next note...
END SUB    		        