前言:stm32f103rct6芯片,TIM4_CH3 (PB8); 中断内统计脉冲个数,如果介意中断太多太频繁占用cpu资源,或其他功能带的比较多,此方法不是好方法。(最近写这东西才发现认认真真看寄存器配置多重要,才有认认真真看stm32中文参考手册)
用此(输出比较模式)驱动步进电机转动指定角度,以前用pwm模式写过步进电机的加减速控制
一、通用定时器输出比较模式
二、定时器初始化配置
//TIM4 PWM部分初始化
//PWM输出初始化
//arr:自动重装值
//psc:时钟预分频数
void TIM4_PWM_Init(u16 arr,u16 psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO, ENABLE);
TIM_TimeBaseStructInit(&TIM_TimeBaseStructure); //设置缺省值,这一步最好加上
TIM_TimeBaseStructure.TIM_Period = arr; //自动重装载寄存器周期的值,溢出值
TIM_TimeBaseStructure.TIM_Prescaler =psc; //时钟频率预分频值
TIM_TimeBaseStructure.TIM_ClockDivision = 0; //设置时钟分割,不分割,可不写
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数模式
//TIM_TimeBaseStructure.TIM_RepetitionCounter=0; //设置重复溢出次数,就是多少次溢出后进入中断,一般为0,只有高级定时器才有用
TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_ResetBits(GPIOB,GPIO_Pin_8); //当计数器CNT与CCRx匹配时翻转该引脚电平
TIM_OCStructInit(&TIM_OCInitStructure); //设置缺省值,这一步最好加上
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Toggle; //翻转模式定时器引脚同时输出pwm
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //输出极性:TIM输出比较极性高
TIM_OC3Init(TIM4, &TIM_OCInitStructure);
TIM_OC3PreloadConfig(TIM4, TIM_OCPreload_Enable);
//中断分组初始化
NVIC_InitStructure.NVIC_IRQChannel = TIM4_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_ITConfig(TIM4, TIM_IT_CC3, ENABLE); //设置寄存器TIM4->DIER CC3IE位允许捕获/比较3中断;CC3DE位允许捕获/比较3中断的DMA请求
TIM_Cmd(TIM4,ENABLE); //启动定时器3 TIM3_CR1[0]=1;
}
三、中断处理函数
void TIM4_IRQHandler(void)
{
static u32 pulse = 0;
if (TIM_GetITStatus(TIM4, TIM_IT_CC3) != RESET)
{
TIM_ClearITPendingBit(TIM4,TIM_IT_CC3);
pulse++;
if(pulse > 12800)
{
TIM_Cmd(TIM4, DISABLE);
pulse = 0;
}
}
}
这里设置的是12800脉冲,由于步进电机步距角为1.8度(即1个脉冲转动1.8度),细分设置为64,则
64个脉冲转动1.8度,360*64/1.8 = 12800脉冲
|