Beep using PWM and speaker

Dependents:   Hangman Weather_Station Ultrasonic Ultrasonicdistancesensor ... more

Committer:
pprasad7
Date:
Thu Oct 11 20:14:49 2012 +0000
Revision:
0:080ef5594cce
beep;

Who changed what in which revision?

UserRevisionLine numberNew contents of line
pprasad7 0:080ef5594cce 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) {
pprasad7 0:080ef5594cce 31 _pwm.write(0.0); // after creating it have to be off
pprasad7 0:080ef5594cce 32 }
pprasad7 0:080ef5594cce 33
pprasad7 0:080ef5594cce 34 /** stop the beep instantaneous
pprasad7 0:080ef5594cce 35 * usually not used
pprasad7 0:080ef5594cce 36 */
pprasad7 0:080ef5594cce 37 void Beep::nobeep() {
pprasad7 0:080ef5594cce 38 _pwm.write(0.0);
pprasad7 0:080ef5594cce 39 }
pprasad7 0:080ef5594cce 40
pprasad7 0:080ef5594cce 41 /** Beep with given frequency and duration.
pprasad7 0:080ef5594cce 42 *
pprasad7 0:080ef5594cce 43 * @param frequency - the frequency of the tone in Hz
pprasad7 0:080ef5594cce 44 * @param time - the duration of the tone in seconds
pprasad7 0:080ef5594cce 45 */
pprasad7 0:080ef5594cce 46
pprasad7 0:080ef5594cce 47 void Beep::beep(float freq, float time) {
pprasad7 0:080ef5594cce 48
pprasad7 0:080ef5594cce 49 _pwm.period(1.0/freq);
pprasad7 0:080ef5594cce 50 _pwm.write(0.5); // 50% duty cycle - beep on
pprasad7 0:080ef5594cce 51 toff.attach(this,&Beep::nobeep, time); // time to off
pprasad7 0:080ef5594cce 52 }
pprasad7 0:080ef5594cce 53
pprasad7 0:080ef5594cce 54
pprasad7 0:080ef5594cce 55
pprasad7 0:080ef5594cce 56