为了获得额外的一个pwm波形,就使用了tim16作为pwm的源,结果愣是掉坑里出不来,花了2个多小时才搞定。
具体自己看代码吧,懒得多写了。
void STM_BSP_TIM16_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure= { 0 };
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource8, GPIO_AF_2);//GPIO_PinAFConfig(GPIOB, GPIO_PinSource0, GPIO_AF_1);
/* Compute the value to be set in ARR regiter to generate signal frequency at 1 Khz */
uint16_t TimerPeriod = (SystemCoreClock / 40000 ) - 1;
/* Compute CCR3 value to generate a duty cycle at 100% for channel 3 */
uint16_t Channel1Pulse = 0;//(uint16_t) (((uint32_t) 1000 * (TimerPeriod - 1)) / 1000);
//uint16_t Channel2Pulse = 0;//(uint16_t) (((uint32_t) 1000 * (TimerPeriod - 1)) / 1000);
/* TIM3 clock enable */
//RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3 , ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM16, ENABLE);
/* Time Base configuration */
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_Period = TimerPeriod;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM16, &TIM_TimeBaseStructure);
/* Channel 3 Configuration in PWM mode */
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = Channel1Pulse;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
TIM_OC1Init(TIM16, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM16,TIM_OCPreload_Enable);
TIM_ARRPreloadConfig(TIM16,ENABLE);
// TIM_OCInitStructure.TIM_Pulse = Channel2Pulse;
// TIM_OC2Init(TIM3, &TIM_OCInitStructure);
/* TIM3 counter enable */
TIM_Cmd(TIM16, ENABLE);
/* TIM3 Main Output Enable */
TIM_CtrlPWMOutputs(TIM16, ENABLE);
}
void STM_BSP_TIM16_CH1_Pulse(uint16_t Pulse)
{
TIM_OCInitTypeDef TIM_OCInitStructure={0};
/* Compute the value to be set in ARR regiter to generate signal frequency at 1 Khz */
uint16_t TimerPeriod = (SystemCoreClock / 40000 ) - 1;
/* Compute CCR2 value to generate a duty cycle at Pulse% for channel 4 */
uint16_t Channel1Pulse = (uint16_t) (((uint32_t) Pulse * (TimerPeriod - 1)) / 1000);
/* Channel 3 Configuration in PWM mode */
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = Channel1Pulse;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
TIM_OC1Init(TIM16, &TIM_OCInitStructure);
TIM_Cmd(TIM16, ENABLE);
TIM_CtrlPWMOutputs(TIM16, ENABLE);
}