Plays a song using PWM and timer interrupts. Returns once song starts.

Dependencies:   mbed

Fork of speaker_demo_PWM by jim hamblen

Committer:
4180_1
Date:
Tue Oct 21 03:00:15 2014 +0000
Revision:
1:2e6ea42675c7
ver 1.0

Who changed what in which revision?

UserRevisionLine numberNew contents of line
4180_1 1:2e6ea42675c7 1 #include "mbed.h"
4180_1 1:2e6ea42675c7 2 // new class to play a note on Speaker based on PwmOut class
4180_1 1:2e6ea42675c7 3 class SongPlayer
4180_1 1:2e6ea42675c7 4 {
4180_1 1:2e6ea42675c7 5 public:
4180_1 1:2e6ea42675c7 6 SongPlayer(PinName pin) : _pin(pin) {
4180_1 1:2e6ea42675c7 7 // _pin(pin) means pass pin to the constructor
4180_1 1:2e6ea42675c7 8 }
4180_1 1:2e6ea42675c7 9 // class method to play a note based on PwmOut class
4180_1 1:2e6ea42675c7 10 void PlaySong(float frequency[], float duration[], float volume=1.0) {
4180_1 1:2e6ea42675c7 11 vol = volume;
4180_1 1:2e6ea42675c7 12 notecount = 0;
4180_1 1:2e6ea42675c7 13 _pin.period(1.0/frequency[notecount]);
4180_1 1:2e6ea42675c7 14 _pin = volume/2.0;
4180_1 1:2e6ea42675c7 15 noteduration.attach(this,&SongPlayer::nextnote, duration[notecount]);
4180_1 1:2e6ea42675c7 16 // setup timer to interrupt for next note to play
4180_1 1:2e6ea42675c7 17 frequencyptr = frequency;
4180_1 1:2e6ea42675c7 18 durationptr = duration;
4180_1 1:2e6ea42675c7 19 //returns after first note starts to play
4180_1 1:2e6ea42675c7 20 }
4180_1 1:2e6ea42675c7 21 void nextnote();
4180_1 1:2e6ea42675c7 22 private:
4180_1 1:2e6ea42675c7 23 Timeout noteduration;
4180_1 1:2e6ea42675c7 24 PwmOut _pin;
4180_1 1:2e6ea42675c7 25 int notecount;
4180_1 1:2e6ea42675c7 26 float vol;
4180_1 1:2e6ea42675c7 27 float * frequencyptr;
4180_1 1:2e6ea42675c7 28 float * durationptr;
4180_1 1:2e6ea42675c7 29 };
4180_1 1:2e6ea42675c7 30 //Interrupt Routine to play next note
4180_1 1:2e6ea42675c7 31 void SongPlayer::nextnote()
4180_1 1:2e6ea42675c7 32 {
4180_1 1:2e6ea42675c7 33 _pin = 0.0;
4180_1 1:2e6ea42675c7 34 notecount++; //setup next note in song
4180_1 1:2e6ea42675c7 35 if (durationptr[notecount]!=0.0) {
4180_1 1:2e6ea42675c7 36 _pin.period(1.0/frequencyptr[notecount]);
4180_1 1:2e6ea42675c7 37 noteduration.attach(this,&SongPlayer::nextnote, durationptr[notecount]);
4180_1 1:2e6ea42675c7 38 _pin = vol/2.0;
4180_1 1:2e6ea42675c7 39 } else
4180_1 1:2e6ea42675c7 40 _pin = 0.0; //turn off on last note
4180_1 1:2e6ea42675c7 41 }