Note: Use the TIMER1 CH1 that is PA8 port output PWM driver buzzer. The following is the code (applied on stm32f103)
void Fn_pwm_init (int16u _pwmfreq)
{
Todo:add Your code here:
/* Timer1 Channel 1, PA8 IO initialization */
Gpio_pinremapconfig (gpio_partialremap_tim1,enable);
Gpio_inittypedef gpio_initstructure;
Gpio_initstructure.gpio_pin = Gpio_pin_8;
Gpio_initstructure.gpio_mode = gpio_mode_af_pp;
Gpio_initstructure.gpio_speed = Gpio_speed_50mhz;
Gpio_init (Gpioa, &gpio_initstructure);
RCC TIM1 and IO clock open
Rcc_apb2periphclockcmd (RCC_APB2PERIPH_TIM1, ENABLE);
Rcc_apb2periphclockcmd (Rcc_apb2periph_gpioa | rcc_apb2periph_afio,enable);
The following is the TIM1 initialization
Tim_timebaseinittypedef tim_timebasestructure;
To reset the timer to the default value
Tim_deinit (TIM1);
Clock source supplied to TIM1 with internal clock
Tim_internalclockconfig (TIM1);
The Prescaler factor is 0, that is, no prescaler at this time the timer frequency is 48MHz
Tim_timebasestructure.tim_prescaler = 1-1;//1 frequency, i.e. no crossover
Set up Clock segmentation
Tim_timebasestructure.tim_clockdivision = TIM_CKD_DIV1;
Set counter mode to up counting mode
Tim_timebasestructure.tim_countermode = tim_countermode_up;
Set the count overflow size 48000000 to the system clock
Tim_timebasestructure.tim_period = (48000000/_pwmfreq)-1;
To apply a configuration to TIM1
Tim_timebaseinit (tim1,&tim_timebasestructure);
PWM initialization
Tim_ocinittypedef timocinitstructure; Set default values
Tim_ocstructinit (&timocinitstructure); PWM Mode 1 output
Timocinitstructure.tim_ocmode = TIM_OCMODE_PWM1; Set duty Duty ratio = (Ccrx/arr) *100% or (tim_pulse/tim_period) *100%
Timocinitstructure.tim_pulse = 50 * 4800/100; 50 is 100 ratio, 1-100
timocinitstructure.tim_ocpolarity = Tim_ocpolarity_high; Enable to output state
Timocinitstructure.tim_outputstate = tim_outputstate_enable; CH1 output of TIM1
Tim_oc1init (TIM1, &timocinitstructure); Set the PWM output of the TIM1 to enable
Tim_ctrlpwmoutputs (tim1,disable);
}
void Fn_pwm_cmd (Functionalstate newstate)
{
Todo:add Your code here:
Tim_ctrlpwmoutputs (TIM1, newstate);
Tim_cmd (TIM1, newstate);
}