@@ -214,7 +214,7 @@ void setup_spi_low_speed(void)
214214 * @see Reference manual (RM0008) "TIMx functional description" and in
215215 * particular "PWM mode" section.
216216 */
217- static void setup_pwm (void )
217+ static void setup_motor_driver (void )
218218{
219219 timer_set_mode (TIM3 , TIM_CR1_CKD_CK_INT , TIM_CR1_CMS_EDGE ,
220220 TIM_CR1_DIR_UP );
@@ -248,6 +248,44 @@ static void setup_pwm(void)
248248 timer_enable_counter (TIM3 );
249249}
250250
251+ /**
252+ * @brief Setup PWM for the speaker.
253+ *
254+ * TIM1 is used to generate the PWM signals for the speaker:
255+ *
256+ * - Configure channel 3 as output GPIO.
257+ * - Edge-aligned, up-counting timer.
258+ * - Prescale to increment timer counter at TIM1CLK_FREQUENCY_HZ.
259+ * - Set output compare mode to PWM1 (output is active when the counter is
260+ * less than the compare register contents and inactive otherwise.
261+ * - Disable output compare output (speaker is off by default).
262+ * - Enable outputs in the break subsystem.
263+ *
264+ * @see Reference manual (RM0008) "TIMx functional description" and in
265+ * particular "PWM mode" section.
266+ */
267+ static void setup_speaker (void )
268+ {
269+ gpio_set_mode (GPIOA , GPIO_MODE_OUTPUT_50_MHZ ,
270+ GPIO_CNF_OUTPUT_ALTFN_PUSHPULL , GPIO_TIM1_CH3 );
271+
272+ rcc_periph_reset_pulse (RST_TIM1 );
273+
274+ timer_set_mode (TIM1 , TIM_CR1_CKD_CK_INT , TIM_CR1_CMS_EDGE ,
275+ TIM_CR1_DIR_UP );
276+
277+ timer_set_prescaler (TIM1 ,
278+ (rcc_apb2_frequency / TIM1CLK_FREQUENCY_HZ - 1 ));
279+ timer_set_repetition_counter (TIM1 , 0 );
280+ timer_enable_preload (TIM1 );
281+ timer_continuous_mode (TIM1 );
282+
283+ timer_disable_oc_output (TIM1 , TIM_OC3 );
284+ timer_set_oc_mode (TIM1 , TIM_OC3 , TIM_OCM_PWM1 );
285+
286+ timer_enable_break_main_output (TIM1 );
287+ }
288+
251289/**
252290 * @brief Configure timer to read a quadrature encoder.
253291 *
@@ -373,7 +411,8 @@ void setup(void)
373411 setup_adc1 ();
374412 setup_usart ();
375413 setup_encoders ();
376- setup_pwm ();
414+ setup_motor_driver ();
415+ setup_speaker ();
377416 setup_mpu ();
378417 setup_systick ();
379418}
0 commit comments