4 #include "AudioPWM/PWMAudioBase.h"
5 #include "AudioTimer/AudioTimer.h"
15 using PWMDriver = PWMDriverSTM32;
28 HardwareTimer *p_timer;
37 PWMPin(HardwareTimer *p_timer,
int channel,
int pin,
int maxValue,
38 int pwmFrequency = 30000) {
39 this->p_timer = p_timer;
40 this->channel = channel;
42 this->max_value = maxValue;
43 this->pwm_frequency = pwmFrequency;
48 p_timer->setPWM(channel, pin, pwm_frequency,
53 void setRate(
int rate) {
55 uint16_t sample = 100.0 * rate / max_value;
56 p_timer->setCaptureCompare(channel, sample,
57 PERCENT_COMPARE_FORMAT);
66 void begin(HardwareTimer *pwm_timer,
int pwm_frequency,
int maxValue) {
67 this->p_timer = pwm_timer;
68 this->pwm_frequency = pwm_frequency;
69 this->max_value = maxValue;
77 bool addPin(
int pin) {
78 LOGI(
"addPin: %d", pin);
79 TIM_TypeDef *p_instance = (TIM_TypeDef *)pinmap_peripheral(
80 digitalPinToPinName(pin), PinMap_PWM);
81 channel = STM_PIN_CHANNEL(
82 pinmap_function(digitalPinToPinName(pin), PinMap_PWM));
83 PWMPin pwm_pin{p_timer, channel, pin, max_value, pwm_frequency};
84 pins.push_back(pwm_pin);
86 if (p_timer->getHandle()->Instance != p_instance) {
87 LOGE(
"Invalid pin %d with timer %s for timer %s", pin,
88 getTimerStr(p_instance),
89 getTimerStr(p_timer->getHandle()->Instance));
92 LOGI(
"Using Timer %s for PWM", getTimerStr(p_instance));
93 pins[pins.size() - 1].begin();
97 void setRate(
int idx,
int rate) {
98 if (idx < pins.size()) {
99 pins[idx].setRate(rate);
101 LOGE(
"Invalid index: %d", idx);
106 HardwareTimer *p_timer;
112 const char *getTimerStr(TIM_TypeDef *inst) {
115 else if (inst == TIM2)
117 else if (inst == TIM3)
119 else if (inst == TIM4)
121 else if (inst == TIM5)
130 ticker.setTimer(PWM_FREQ_TIMER_NO);
134 virtual void end()
override {
139 is_timer_started =
false;
140 if (buffer !=
nullptr) {
151 HardwareTimer *p_pwm_timer =
nullptr;
158 if (!is_timer_started) {
161 ticker.setCallbackParameter(
this);
163 is_timer_started =
true;
172 if (p_pwm_timer ==
nullptr) {
173 p_pwm_timer =
new HardwareTimer(PWM_DEFAULT_TIMER);
178 pwm.begin(p_pwm_timer, audio_config.pwm_frequency,
maxOutputValue());
179 for (
auto gpio : audio_config.pins()) {
180 LOGD(
"Processing channel %d -> pin: %d", ch++, gpio);
185 virtual void setupTimer() {}
197 pwm.setRate(channel, value);
203 if (accessAudioPWM !=
nullptr) {