Simple tool for PWM piezo speaker
Diff: Piezo.cpp
- Revision:
- 0:39de01daa2de
diff -r 000000000000 -r 39de01daa2de Piezo.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Piezo.cpp Sat Oct 01 19:09:55 2016 +0000 @@ -0,0 +1,41 @@ +#include "Piezo.h" + +Piezo::Piezo(PinName Pwmout):_pwm(Pwmout) +{ + min_freq = 1.0; + max_freq = 20000.0; + + _pwm.period(1); + _pwm.write(0.0); +} + +void Piezo::play(float frequency, int duration_ms) +{ + float Frequency = (frequency < min_freq)? min_freq : frequency; + Frequency = (frequency > max_freq)? max_freq : frequency; + + Period = 1.0/Frequency; + + _pwm.period(Period); + _pwm.write(0.5); + wait_ms(duration_ms); + _pwm.write(0.0); +} + +void Piezo::playAsync(float frequency, int duration_ms) +{ + float Frequency = (frequency < min_freq)? min_freq : frequency; + Frequency = (frequency > max_freq)? max_freq : frequency; + + Period = 1.0/Frequency; + + _pwm.period(Period); + _pwm.write(0.5); + _timer.detach(); + _timer.attach_us(this,&Piezo::stop, duration_ms*1000); +} + +void Piezo::stop(void) +{ + _pwm.write(0.0); +} \ No newline at end of file