STM32F4 PWM和中断用同一个定时器
Posted
技术标签:
【中文标题】STM32F4 PWM和中断用同一个定时器【英文标题】:STM32F4 PWM and interrupt with the same timer 【发布时间】:2017-02-17 10:39:21 【问题描述】:我有一个 STM32F407x。如果达到 UPPER 值,是否可以在引脚上有 PWM 信号并同时获得定时器中断?我尝试了以下代码,但我只得到一次中断(如果我使用调试器,计数将永远保持在 1),但 PWM 信号在 PB6 上仍然可用:
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】:如果您尝试计算脉搏数或在某个脉搏处停止,这篇文章可能会有所帮助
Stop PWM output after N steps
【讨论】:
以上是关于STM32F4 PWM和中断用同一个定时器的主要内容,如果未能解决你的问题,请参考以下文章