gpt4 book ai didi

c - STM32F4 PWM和中断用同一个定时器

转载 作者:行者123 更新时间:2023-11-30 16:56:23 27 4
gpt4 key购买 nike

我有一个 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;
}
}

最佳答案

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

Stop PWM output after N steps

关于c - STM32F4 PWM和中断用同一个定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39934030/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com