Simple PWM / beep generation library. Supports timed-duration beeps or infinite length tone generation.
Dependents: PseudoTheremin NSDL_HelloWorld_WiFi UbloxModemNanoServiceClient IOT-NSDL_HelloWorld ... more
Revision 0:3eb39e374fc3, committed 2013-07-31
- Comitter:
- shimniok
- Date:
- Wed Jul 31 23:05:44 2013 +0000
- Commit message:
- Working version with dual sharp rangers and A2D I2C adapters
Changed in this revision
Beep.cpp | Show annotated file Show diff for this revision Revisions of this file |
Beep.h | Show annotated file Show diff for this revision Revisions of this file |
diff -r 000000000000 -r 3eb39e374fc3 Beep.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Beep.cpp Wed Jul 31 23:05:44 2013 +0000 @@ -0,0 +1,29 @@ +#include "mbed.h" +#include "Beep.h" + +/** Create a Beep object connected to the specified PwmOut pin + * + * @param pin PwmOut pin to connect to + */ +Beep::Beep(PinName pin) : _pwm(pin) { + _pwm.write(0.0); // after creating it have to be off +} + + /** Stop the beep instantaneously. + */ +void Beep::nobeep() { + _pwm.write(0.0); +} + +/** Beep with given frequency and duration. + * + * @param frequency - the frequency of the tone in Hz + * @param time - the duration of the tone in seconds, 0 runs indefinitely + */ +void Beep::beep(float freq, float time) { + + _pwm.period(1.0/freq); + _pwm.write(0.5); // 50% duty cycle - beep on + if (time > 0) + toff.attach(this,&Beep::nobeep, time); // time to off +}
diff -r 000000000000 -r 3eb39e374fc3 Beep.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Beep.h Wed Jul 31 23:05:44 2013 +0000 @@ -0,0 +1,49 @@ +#ifndef MBED_BEEP_H +#define MBED_BEEP_H + +#include "mbed.h" + +/** Generates a tone with a buzzer, based on a PwmOut + * The class use a timeout to switch off the sound - it is not blocking while making noise + * + * Example: + * @code + * // Beep at 2kHz for 0.5 seconds + * #include "mbed.h" + * #include "Beep.h" + * + * Beep buzzer(p21); + * + * int main() { + * ... + * buzzer.beep(2000,0.5); + * ... + * } + * @endcode + */ +class Beep { + +public: + +/** Create a Beep object connected to the specified PwmOut pin + * + * @param pin PwmOut pin to connect to + */ + Beep(PinName pin); + +/** Beep with given frequency and duration. + * + * @param frequency - the frequency of the tone in Hz + * @param time - the duration of the tone in seconds + */ + void beep(float frequency, float time=0); + +/** stop the beep instantaneously. Not typically needed, but here just in case + */ + void nobeep(); + +private : + PwmOut _pwm; + Timeout toff; +}; +#endif