请教各位:1.定时器做计数用的话还需要设自动重装载值吗?就是TIM_TimeBaseInit不需要初始化了吧
2.如果用TIM5做定时器,定时作用,TIM2编码器接口模式,TIM5定时中断,然后读取TIM2的计数值,就是脉冲数了吧
3.大家一般怎么测编码器脉冲数
刚开始学不太懂,贴上代码,看看可以实现2的功能吗
u32 code1,code2,code3;
/*编码器模式,脉冲计数*/
void TIM2345(u32 arr,u16 psc)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
NVIC_InitTypeDef NVIC_InitStruct;
GPIO_InitTypeDef GPIO_InitStructure;
//使能时钟
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5,ENABLE);
//初始化GPIO
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15 | GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_Init(GPIOB, &GPIO_InitStructure);
//TIM5定时
TIM_DeInit(TIM5);
TIM_TimeBaseInitStruct.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseInitStruct.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseInitStruct.TIM_Period=arr;
TIM_TimeBaseInitStruct.TIM_Prescaler=psc;
TIM_TimeBaseInit(TIM5,&TIM_TimeBaseInitStruct);
//TIM2计数
TIM_DeInit(TIM2);
TIM_CounterModeConfig(TIM2,TIM_CounterMode_Up);
//编码器接口模式
TIM_EncoderInterfaceConfig(TIM2,TIM_EncoderMode_TI12,TIM_ICPolarity_BothEdge,TIM_ICPolarity_BothEdge);
NVIC_InitStruct.NVIC_IRQChannel=TIM5_IRQn;
NVIC_InitStruct.NVIC_IRQChannelCmd=ENABLE;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority=0x03;
NVIC_InitStruct.NVIC_IRQChannelSubPriority=0x03;
NVIC_Init(&NVIC_InitStruct);
//使能定时器,使能5中断
TIM_Cmd(TIM2,ENABLE);
TIM_Cmd(TIM5,ENABLE);
TIM_ITConfig(TIM5,TIM_IT_Update,ENABLE);
TIM_SetCounter(TIM2,0);
}
//读取234计数值,并清零
void TIM5_IRQHandler()
{
code1=TIM2->CNT;
code2=TIM3->CNT;
code3=TIM4->CNT;
TIM_SetCounter(TIM2,0);
TIM_SetCounter(TIM3,0);
TIM_SetCounter(TIM4,0);
}
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
一周热门 更多>