STM32F4 PWM和中断使用相同的定时器

时间:2016-10-08 15:17:19

标签: c microcontroller interrupt stm32 pwm

我有STM32F407x。如果达到UPPER值,是否可以在引脚上设置PWM信号并同时获得定时器中断?我尝试了下面的代码,但是我只得到一次中断(如果我使用调试器,则计数永远保持在1),但PB6仍然可以使用PWM信号:

volatile int count=0;


void TM_LEDS_Init(void) {
    GPIO_InitTypeDef GPIO_InitStruct;

    /* Clock for GPIOB */
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);

    /* Alternating functions for pins */
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource6, GPIO_AF_TIM4);

    /* Set pins */
    GPIO_InitStruct.GPIO_Pin = GPIO_Pin_6;
    GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_100MHz;
    GPIO_Init(GPIOB, &GPIO_InitStruct);


}

void TM_TIMER_Init(void) {
    TIM_TimeBaseInitTypeDef TIM_BaseStruct;

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);

    TIM_BaseStruct.TIM_Prescaler = 100;
    TIM_BaseStruct.TIM_CounterMode = TIM_CounterMode_Up;

    TIM_BaseStruct.TIM_Period = 256; 
    TIM_BaseStruct.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_BaseStruct.TIM_RepetitionCounter = 0;
    TIM_TimeBaseInit(TIM4, &TIM_BaseStruct);

}

void TM_PWM_Init(void) {
    TIM_OCInitTypeDef TIM_OCStruct;

    TIM_OCStruct.TIM_OCMode = TIM_OCMode_PWM2;
    TIM_OCStruct.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCStruct.TIM_OCPolarity = TIM_OCPolarity_Low;

    TIM_OCStruct.TIM_Pulse = 150; /* 25% duty cycle */
    TIM_OC1Init(TIM4, &TIM_OCStruct);
    TIM_OC1PreloadConfig(TIM4, TIM_OCPreload_Enable);

    /* Clear Interrupt */
    for(int i=0; i<3; i++)
    if (TIM_GetITStatus(TIM4, TIM_IT_Update) != RESET)
      TIM_ClearITPendingBit(TIM4, TIM_IT_Update);

    /* Enable Interrupt */
    TIM_ITConfig(TIM4, TIM_IT_Update, ENABLE);

    TIM_Cmd(TIM4, ENABLE);

}

void configNVIC(void)
{
    NVIC_InitTypeDef initNVICStruct;

    /* Enable the TIM2 global Interrupt */
    initNVICStruct.NVIC_IRQChannel = TIM4_IRQn;
    initNVICStruct.NVIC_IRQChannelPreemptionPriority = 1;
    initNVICStruct.NVIC_IRQChannelSubPriority = 3;
    initNVICStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&initNVICStruct);

}

void TIM4_IRQHandler(void) //This Interrupt changes changes state from x to x+-1
{
    if (TIM_GetITStatus(TIM4, TIM_IT_Update) != RESET)
    {
        TIM_ClearITPendingBit(TIM4, TIM_IT_Update);
        count++;

    }
}



int main(void) {
    /* Initialize system */
    SystemInit();
    configNVIC();
    /* Init leds */
    TM_LEDS_Init();
    /* Init timer */
    TM_TIMER_Init();
    /* Init PWM */
    TM_PWM_Init();

    int i=0;
    while (1) {
        i=count;
    }
}

1 个答案:

答案 0 :(得分:0)

如果您正在尝试计算脉冲或停止某个脉冲,这篇文章可能会有所帮助

Stop PWM output after N steps

相关问题