STM32比较输出PMW频率改变的问题
时间:10-02
整理:3721RD
点击:
因为需要控制步进电机的转速,所以要实时改变PMW的频率。我用输出比较的方法输出一路PMW波形。具体程序如下 :
TIM4配置:
void TIM4_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7|GPIO_Pin_8|
GPIO_Pin_9|GPIO_Pin_6;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
NVIC_InitStructure.NVIC_IRQChannel = TIM4_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_TimeBaseStructure.TIM_Period = 65535;
TIM_TimeBaseStructure.TIM_Prescaler = 29;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Toggle;
TIM_OCInitStructure.TIM_OutputState =
TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 240;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
TIM_OC1Init(TIM4, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM4, TIM_OCPreload_Disable);
TIM_ARRPreloadConfig(TIM4, DISABLE);
TIM_Cmd(TIM4, ENABLE);
TIM_ITConfig(TIM4,TIM_IT_CC1|TIM_IT_CC2|TIM_IT_CC3|
TIM_IT_CC4, ENABLE);
}
TIM4中断函数:
void TIM4_IRQHandler(void)
{
u16 capture ;
if (TIM_GetITStatus(TIM4, TIM_IT_CC1) != RESET)
{
TIM_ClearITPendingBit(TIM4, TIM_IT_CC1);
capture = TIM_GetCapture1(TIM4);
TIM4_Aim_Counter1 = (CmdCode[2] << 8) | CmdCode[3];
TIM4_Aim_Counter2 = (CmdCode[4] << 8) | CmdCode[5];
TIM_SetCompare1(TIM4,capture + TIM4_Aim_Counter1);
TIM4_CH4_Counter++;
if(TIM4_CH4_Counter >= TIM4_Aim_Counter2 )
{
TIM_Cmd(TIM4, DISABLE);
TIM4_CH4_Counter = 0;
for(i = 0;i < 10;i++)
{
CmdCode[i] = 0;
}
}
}
}
程序如上面所示。我之前做过实验,通过改变TIM4_Aim_Counter1的来改变PMW的输出频率,并且成功的,波形的占空比都是50%
比如TIM4_Aim_Counter1的值为150,输出PMW频率为8KHz,TIM4_Aim_Counter1的值为300,输出PMW频率为4KHz.但是很多人说改变这个TIM4_Aim_Counter1只能改变占空比不能改频率。但是我这个怎么能改呢?如果我想实时的改变PMW的输出频率,改怎么改呢?
如下图所示。
8KHz,占空比为50%对应TIM4_Aim_Counter1为150
4KHz,占空比为50%对应TIM4_Aim_Counter1为300
大家看看啊,我用的库是V3.3.0的
谢谢小编的分享了哟
通过修改占空比的份数,就能改变频率吧