Simple tool for PWM piezo speaker
Piezo.cpp
- Committer:
- TeaPack_CZ
- Date:
- 2016-10-01
- Revision:
- 0:39de01daa2de
File content as of revision 0:39de01daa2de:
#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); }