4 #include "AudioTools/CoreAudio/AudioPWM/PWMAudioBase.h"
5 #include "AudioTools/CoreAudio/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;
76 bool addPin(
int pin) {
77 LOGI(
"addPin: %d", pin);
78 TIM_TypeDef *p_instance = (TIM_TypeDef *)pinmap_peripheral(
79 digitalPinToPinName(pin), PinMap_PWM);
80 channel = STM_PIN_CHANNEL(
81 pinmap_function(digitalPinToPinName(pin), PinMap_PWM));
82 PWMPin pwm_pin{p_timer, channel, pin, max_value, pwm_frequency};
83 pins.push_back(pwm_pin);
85 if (p_timer->getHandle()->Instance != p_instance) {
86 LOGE(
"Invalid pin %d with timer %s for timer %s", pin,
87 getTimerStr(p_instance),
88 getTimerStr(p_timer->getHandle()->Instance));
91 LOGI(
"Using Timer %s for PWM", getTimerStr(p_instance));
92 pins[pins.size() - 1].begin();
96 void setRate(
int idx,
int rate) {
97 if (idx < pins.size()) {
98 pins[idx].setRate(rate);
100 LOGE(
"Invalid index: %d", idx);
105 HardwareTimer *p_timer;
111 const char *getTimerStr(TIM_TypeDef *inst) {
114 else if (inst == TIM2)
116 else if (inst == TIM3)
118 else if (inst == TIM4)
120 else if (inst == TIM5)
129 ticker.setTimer(PWM_FREQ_TIMER_NO);
133 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) {