stm32的通用计数器用于编码器的脉冲计数
2018-07-19 来源:eefocus
这周做电脑鼠的编码器模块,整整的折腾了一周。
这过程真是让我们哭笑不得,我们打算用TIM3的CH3和CH4通道采集左电机的pwm来测速和测距,用TIM4的CH2和CH1来测右电机的。
写代码时,我们先做的是左电机的,整整闹到了礼拜五,才发现通用定时器的CH3和CH4通道不能用来做PWM输入,晕!!下面是我们的配置之一,拿出来与大家分享分享!
我们用GPIO_B_7,TIMER4的二通道
void MY_CONFIG(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
/* TIM4 clock source enable */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
/* Enable GPIOA, clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
//TIM4输出初始化
TIM_DeInit(TIM4);
TIM_TimeBaseStructure.TIM_Period = 100; //计数值=100-1
TIM_TimeBaseStructure.TIM_Prescaler = 0; //预分频
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //时钟分割
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Down; //模式
TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure); //基本初始化
TIM_SetCounter(TIM4, 100); //设置 TIM4 计数器寄存器值
//设置 TIMx 自动重装载寄存器值
TIM_ARRPreloadConfig(TIM4, ENABLE);
TIM_SelectInputTrigger(TIM4, TIM_TS_TI2FP2); //若为通道1 ,则为TIM_TS_TI1FP1
//TIM_SelectInputTrigger(TIM2, TIM_TS_TI1F_ED);
TIM_SelectSlaveMode(TIM4, TIM_SlaveMode_External1);
//TIM_SelectSlaveMode(TIM4, TIM_SlaveMode_Reset);
TIM_SetCompare2(TIM4, 100); //若用1通道。则为:TIM_SetComper1(TIM4,100);
TIM_Cmd(TIM4, ENABLE); //启动TIM4
TIM_ClearFlag(TIM4, TIM_IT_CC2); //若用一通道,则此处和后面的TIM_IT_CC2都改为TIM_IT_CC1
TIM_ITConfig(TIM4, TIM_IT_CC2, ENABLE)
//中断配置
NVIC_InitStructure.NVIC_IRQChannel = TIM4_IRQChannel;; //
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3; //抢占优先级0
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //响应优先级0
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //允许中断
NVIC_Init(&NVIC_InitStructure); //写入设置
}
void TIM4_IRQHandler(void)
{
TIM_ClearFlag(TIM4, TIM_IT_CC2);
}
悲催了,还得重新画板子。不过关于stm32的通用定时器学到了不少,继续加油
上一篇:STM32正交编码器接口
下一篇:STM32定时器的编码器模式