使用PWM可以调节灯光的亮度或风扇的转速等,为了便于验证PWM调节的效果,这里使用的是基于功率放大作用的风扇驱动模块,
它与开发板的连接情况如图1所示。
图1 硬件连接
在使用PA6和PA7为PWM输出端口的情况下,其引脚配置函数为:
void GPIO_Configuration(void)
{
GPIO_InitType GPIO_InitStructure;
GPIO_PinAFConfig(GPIOA, GPIO_PinsSource6, GPIO_AF_1);
GPIO_PinAFConfig(GPIOA, GPIO_PinsSource7, GPIO_AF_1);
GPIO_StructInit(&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pins = GPIO_Pins_6 | GPIO_Pins_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_MaxSpeed = GPIO_MaxSpeed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
在占空比为50%和37.5%的情况下,2个通道的参数设置值为:
TMR3 Channel1 duty cycle = (TMR3_CCR1/ TMR3_ARR)* 100 = 50%
TMR3 Channel2 duty cycle = (TMR3_CCR2/ TMR3_ARR)* 100 = 37.5%
图2占空比50%时的效果
图3占空比37% 时的效果
int main(void)
{
RCC_Configuration();
GPIO_Configuration();
PrescalerValue = (uint16_t) (SystemCoreClock / 24000000) - 1;
TMR_TimeBaseStructInit(&TMR_TMReBaseStructure);
TMR_TMReBaseStructure.TMR_Period = 665;
TMR_TMReBaseStructure.TMR_DIV = PrescalerValue;
TMR_TMReBaseStructure.TMR_ClockDivision = 0;
TMR_TMReBaseStructure.TMR_CounterMode = TMR_CounterDIR_Up;
TMR_TimeBaseInit(TMR3, &TMR_TMReBaseStructure);
/* PWM1 Mode configuration: Channel1 */
TMR_OCStructInit(&TMR_OCInitStructure);
TMR_OCInitStructure.TMR_OCMode = TMR_OCMode_PWM1;
TMR_OCInitStructure.TMR_OutputState = TMR_OutputState_Enable;
TMR_OCInitStructure.TMR_Pulse = CCR1_Val;
TMR_OCInitStructure.TMR_OCPolarity = TMR_OCPolarity_High;
TMR_OC1Init(TMR3, &TMR_OCInitStructure);
TMR_OC1PreloadConfig(TMR3, TMR_OCPreload_Enable);
/* PWM1 Mode configuration: Channel2 */
TMR_OCInitStructure.TMR_OutputState = TMR_OutputState_Enable;
TMR_OCInitStructure.TMR_Pulse = CCR2_Val;
TMR_OC2Init(TMR3, &TMR_OCInitStructure);
TMR_OC2PreloadConfig(TMR3, TMR_OCPreload_Enable);
TMR_ARPreloadConfig(TMR3, ENABLE);
TMR_Cmd(TMR3, ENABLE);
while (1);
}
|