speaker: Add pwm functionality and 5 new examples to demonstrate
These changes add the ability to intialize a speaker instance to use a PWM pin instead of a standard GPIO pin in order to emit sounds. The current GPIO functionality is fairly constrained by the implementation -- it only permits playing cerain hardcoded "notes". The PWM support allows one to emit specific frequencies (currently between 50-32Khz) using a PWM pin. Of course, you may still be constrained by the limits of your PWM hardware in the end. There are a few new functions provided to support this PWM mode. To use the PWM mode of speaker, use the speaker_init_pwm() initialization routine instead of speaker_init() (for C). For C++ and the SWIG languages, pass "true" as the second argument to the constructor to enable PWM mode. The default is "false", to match current default behavior (GPIO). Functions that are not related to a given mode (GPIO vs. PWM) will do nothing if not usable in that mode. Signed-off-by: Jon Trulson <jtrulson@ics.com>
This commit is contained in:
@@ -34,12 +34,17 @@
|
||||
|
||||
using namespace upm;
|
||||
|
||||
Speaker::Speaker(int pin) :
|
||||
m_speaker(speaker_init(pin))
|
||||
Speaker::Speaker(int pin, bool usePWM) :
|
||||
m_speaker(nullptr)
|
||||
{
|
||||
if (!m_speaker)
|
||||
throw std::runtime_error(std::string(__FUNCTION__) +
|
||||
": speaker_init() failed.");
|
||||
if (usePWM)
|
||||
m_speaker = speaker_init_pwm(pin);
|
||||
else
|
||||
m_speaker = speaker_init(pin);
|
||||
|
||||
if (!m_speaker)
|
||||
throw std::runtime_error(std::string(__FUNCTION__) +
|
||||
": speaker_init()/speaker_init_pwm() failed.");
|
||||
}
|
||||
|
||||
Speaker::~Speaker()
|
||||
@@ -57,3 +62,26 @@ void Speaker::playSound(char letter, bool sharp, std::string vocalWeight)
|
||||
speaker_play_sound(m_speaker, letter, sharp, vocalWeight.c_str());
|
||||
}
|
||||
|
||||
void Speaker::emit(unsigned int freq, unsigned int emit_ms)
|
||||
{
|
||||
if (speaker_emit(m_speaker, freq, emit_ms))
|
||||
throw std::runtime_error(std::string(__FUNCTION__) +
|
||||
": speaker_emit() failed.");
|
||||
}
|
||||
|
||||
void Speaker::setFrequency(unsigned int freq)
|
||||
{
|
||||
if (speaker_set_frequency(m_speaker, freq))
|
||||
throw std::runtime_error(std::string(__FUNCTION__) +
|
||||
": speaker_set_frequency() failed.");
|
||||
}
|
||||
|
||||
void Speaker::on()
|
||||
{
|
||||
speaker_on(m_speaker);
|
||||
}
|
||||
|
||||
void Speaker::off()
|
||||
{
|
||||
speaker_off(m_speaker);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user