雅特力AT32F413定时器TMR3_CH2输出PWM(PB5)并动态改变占空比
0. PB5 GPIO 初始化
void PWM_GPIO_Init(void)
{
GPIO_InitType GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2PERIPH_GPIOB, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2PERIPH_AFIO, ENABLE);
GPIO_PinsRemapConfig(GPIO_PartialRemap_TMR3,ENABLE);//AFIO_MAP4_TMR3_0010
/* GPIOB Configuration:TMR3 Channel 2 as alternate function push-pull */
GPIO_InitStructure.GPIO_Pins = GPIO_Pins_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_MaxSpeed = GPIO_MaxSpeed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
1.定时器TMR3的PWM输出初始化
//TMR3_CH2 重映射 PB5
void TIM3_Init(void)
{
/* -----------------------------------------------------------------------
TMR3 Configuration: generate 4 PWM signals with 4 different duty cycles:
The TMR3CLK frequency is set to SystemCoreClock (Hz), to get TMR3 counter
clock at 24 MHz the Prescaler is computed as following:
- Prescaler = (TMR3CLK / TMR3 counter clock) - 1
The TMR3 is running at 36 KHz: TMR3 Frequency = TMR3 counter clock/(ARR + 1)
= 24 MHz / 666 = 36 KHz
TMR3 Channel1 duty cycle = (TMR3_CCR1/ TMR3_ARR)* 100 = 50% //333
TMR3 Channel2 duty cycle = (TMR3_CCR2/ TMR3_ARR)* 100 = 37.5% //249
TMR3 Channel3 duty cycle = (TMR3_CCR3/ TMR3_ARR)* 100 = 25% //166
TMR3 Channel4 duty cycle = (TMR3_CCR4/ TMR3_ARR)* 100 = 12.5% //83
----------------------------------------------------------------------- */
TMR_TimerBaseInitType TMR_TMReBaseStructure;
TMR_OCInitType TMR_OCInitStructure;
/* TMR3 clock enable */
RCC_APB1PeriphClockCmd(RCC_APB1PERIPH_TMR3, ENABLE);
/* TMRe base configuration */
TMR_TimeBaseStructInit(&TMR_TMReBaseStructure);
TMR_TMReBaseStructure.TMR_Period = 665;
TMR_TMReBaseStructure.TMR_DIV = (uint16_t) (SystemCoreClock / 24000000) - 1;/* Compute the prescaler value */
TMR_TMReBaseStructure.TMR_ClockDivision = 0;
TMR_TMReBaseStructure.TMR_CounterMode = TMR_CounterDIR_Up;
TMR_TimeBaseInit(TMR3, &TMR_TMReBaseStructure);
/* PWM1 Mode configuration: Channel2 */
TMR_OCStructInit(&TMR_OCInitStructure);
TMR_OCInitStructure.TMR_OCMode = TMR_OCMode_PWM1;
TMR_OCInitStructure.TMR_OutputState = TMR_OutputState_Enable;
TMR_OCInitStructure.TMR_Pulse = 666;//TMR3 Channel2 duty cycle 默认占空比 0
TMR_OCInitStructure.TMR_OCPolarity = TMR_OCPolarity_High;
TMR_OC2Init(TMR3, &TMR_OCInitStructure);
TMR_OC2PreloadConfig(TMR3, TMR_OCPreload_Enable);
TMR_ARPreloadConfig(TMR3, ENABLE);
TMR_Cmd(TMR3, ENABLE); /* TMR3 enable counter */
}
2.在主循环中间隔20ms 运行下面代码改变CC2的值,即可实现LED呼吸灯效果。
int main(void)
{
..省略一些代码....
delay_init();
PWM_GPIO_Init();
TIM3_Init();
..省略一些代码....
while(1)
{
TMR_SetCompare2(TMR3,PWMcnt);
if( flagpwm == 1)
{
PWMcnt++;
if(PWMcnt>666) flagpwm = 0;
}
else
{
PWMcnt--;
if(PWMcnt<1) flagpwm = 1;
}
delay_ms(20);
}
}