Make noise with a piezo buzzer. Use a pwm pin.

Dependents:   GliderFuncTest1 DropTest

Fork of beep by Peter Drescher

Committer:
dreschpe
Date:
Tue Feb 01 19:17:44 2011 +0000
Revision:
2:a34405c20cf5
Parent:
0:18e4a9c978ec
Child:
3:5a8242af60ba
0.3

Who changed what in which revision?

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