Beep using PWM and speaker

Dependents:   20180621_FT813

Fork of beep by Pallavi Prasad

Committer:
JackB
Date:
Mon Jul 23 12:24:59 2018 +0000
Revision:
1:cfc88789e54f
Parent:
beep.cpp@0:080ef5594cce
Beep

Who changed what in which revision?

UserRevisionLine numberNew contents of line
JackB 1:cfc88789e54f 1 #include "Beep.h"
pprasad7 0:080ef5594cce 2 #include "mbed.h"
pprasad7 0:080ef5594cce 3
pprasad7 0:080ef5594cce 4 /** class to make sound with a buzzer, based on a PwmOut
pprasad7 0:080ef5594cce 5 * The class use a timeout to switch off the sound - it is not blocking while making noise
pprasad7 0:080ef5594cce 6 *
pprasad7 0:080ef5594cce 7 * Example:
pprasad7 0:080ef5594cce 8 * @code
pprasad7 0:080ef5594cce 9 * // Beep with 1Khz for 0.5 seconds
pprasad7 0:080ef5594cce 10 * #include "mbed.h"
pprasad7 0:080ef5594cce 11 * #include "beep.h"
pprasad7 0:080ef5594cce 12 *
pprasad7 0:080ef5594cce 13 * Beep buzzer(p21);
pprasad7 0:080ef5594cce 14 *
pprasad7 0:080ef5594cce 15 * int main() {
pprasad7 0:080ef5594cce 16 * ...
pprasad7 0:080ef5594cce 17 * buzzer.beep(1000,0.5);
pprasad7 0:080ef5594cce 18 * ...
pprasad7 0:080ef5594cce 19 * }
pprasad7 0:080ef5594cce 20 * @endcode
pprasad7 0:080ef5594cce 21 */
pprasad7 0:080ef5594cce 22
pprasad7 0:080ef5594cce 23 using namespace mbed;
pprasad7 0:080ef5594cce 24 // constructor
pprasad7 0:080ef5594cce 25 /** Create a Beep object connected to the specified PwmOut pin
pprasad7 0:080ef5594cce 26 *
pprasad7 0:080ef5594cce 27 * @param pin PwmOut pin to connect to
pprasad7 0:080ef5594cce 28 */
pprasad7 0:080ef5594cce 29
pprasad7 0:080ef5594cce 30 Beep::Beep(PinName pin) : _pwm(pin) {
JackB 1:cfc88789e54f 31 float freq = 1046.50;
JackB 1:cfc88789e54f 32 _pwm.period(1.0f/freq);
JackB 1:cfc88789e54f 33 _pwm.write(0.0f); // after creating it have to be off
pprasad7 0:080ef5594cce 34 }
pprasad7 0:080ef5594cce 35
pprasad7 0:080ef5594cce 36 /** stop the beep instantaneous
pprasad7 0:080ef5594cce 37 * usually not used
pprasad7 0:080ef5594cce 38 */
pprasad7 0:080ef5594cce 39 void Beep::nobeep() {
JackB 1:cfc88789e54f 40 _pwm.write(0.0f);
pprasad7 0:080ef5594cce 41 }
pprasad7 0:080ef5594cce 42
pprasad7 0:080ef5594cce 43 /** Beep with given frequency and duration.
pprasad7 0:080ef5594cce 44 *
pprasad7 0:080ef5594cce 45 * @param frequency - the frequency of the tone in Hz
pprasad7 0:080ef5594cce 46 * @param time - the duration of the tone in seconds
pprasad7 0:080ef5594cce 47 */
pprasad7 0:080ef5594cce 48
JackB 1:cfc88789e54f 49 void Beep::beep(float freq, float time)
JackB 1:cfc88789e54f 50 {
JackB 1:cfc88789e54f 51 _pwm.period(1.0f/freq);
JackB 1:cfc88789e54f 52 _pwm.write(0.5f); // 50% duty cycle - beep on
pprasad7 0:080ef5594cce 53 toff.attach(this,&Beep::nobeep, time); // time to off
pprasad7 0:080ef5594cce 54 }
pprasad7 0:080ef5594cce 55
pprasad7 0:080ef5594cce 56
pprasad7 0:080ef5594cce 57
pprasad7 0:080ef5594cce 58