我这边想用stm32的定时器3控制步进电机驱动器发送脉冲。用输出比较模式能输出脉冲。但是发现改变重装载值频率不变。不知道什么问题希望大家回答下。谢谢了。
工程文件我发布在下面了。大家可以看看。
#include "sys.h"
#include "timer.h"
#include "led.h"
void timer3_PWM_init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
//Step1. PB.1口设置为TIM3的OC4输出口
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
//Step3.使能TIM3的输出比较匹配中断
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_TimeBaseStructure.TIM_Prescaler = 71; //分频系数为71 得到真正的时基单元为72M/(71+1)=1M
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数
TIM_TimeBaseStructure.TIM_Period = 0xffff; //自装载值为65535 特殊值
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseInit(TIM3,&TIM_TimeBaseStructure);
/* Channel 4 Configuration in oc mode */
TIM_OCStructInit(&TIM_OCInitStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Toggle; //触发事件 电平翻转
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //开启输出
TIM_OCInitStructure.TIM_Pulse = 10000; //10000
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //输出极性
TIM_OC4Init(TIM3,&TIM_OCInitStructure); //通道4
TIM_ClearFlag(TIM3, TIM_FLAG_CC1|TIM_FLAG_CC2|TIM_FLAG_CC3|TIM_FLAG_CC4);//清中断标志位
TIM_ITConfig(TIM3, TIM_IT_CC4, ENABLE);//TIM3中断源设置,开启相应通道的捕捉比较中断
TIM_Cmd(TIM3, ENABLE);
//TIM_OC4PreloadConfig(TIM3,TIM_OCPreload_Enable);//使能定时器2的通道1预装载寄存器
}
void TIM3_IRQHandler(void)
{
int capture;
u16 led0pwmval=0;
u8 dir=1;
if(TIM_GetITStatus(TIM3,TIM_IT_CC4) == SET)
{
if(dir)led0pwmval++;
else led0pwmval--;
if(led0pwmval>3000)dir=0;
if(led0pwmval==0)dir=1;
TIM_ClearITPendingBit(TIM3, TIM_IT_CC4 );
capture = TIM_GetCapture1(TIM3);
TIM_SetCompare4(TIM3, capture + led0pwmval);
}
}
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
错误:capture = TIM_GetCapture1(TIM3);一个获取通道1, TIM_SetCompare4(TIM3, capture + led0pwmval);一个设置通道4?
一周热门 更多>