3872 Project GT

Dependencies:   MPR121 mbed Servo

Committer:
chenchen2020
Date:
Sun Oct 25 20:53:46 2020 +0000
Revision:
0:fb39f3e8d0d1
V1

Who changed what in which revision?

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