/*- TIM5编码器模式配置 -*/
//TIM_DeInit(TIM5);
TIM_TimeBaseStructure.TIM_Period = 65535;//计次数;
TIM_TimeBaseStructure.TIM_Prescaler = 0;//
TIM_TimeBaseStructure.TIM_ClockDivision =TIM_CKD_DIV1 ;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM5, &TIM_TimeBaseStructure);
TIM_EncoderInterfaceConfig(TIM5, TIM_EncoderMode_TI12, TIM_ICPolarity_BothEdge ,TIM_ICPolarity_BothEdge); //配置编码器模式触发源和极性
TIM_ICInitStructure.TIM_Channel = TIM_Channel_1; //CC1S=01 选择输入端 IC1映射到TI2上
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_BothEdge; //上升沿捕获
TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI; //映射到TI2上
TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1; //配置输入分频,不分频?
TIM_ICInitStructure.TIM_ICFilter = 0x01;//IC1F=0000 配置输入滤波器 不滤
TIM_ICInit(TIM5, &TIM_ICInitStructure);
NVIC_InitStructure.NVIC_IRQChannel = TIM5_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=2 ;//抢占优先级2
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //子优先级3
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道使能
NVIC_Init(&NVIC_InitStructure); //根据指定的参数初始化VIC寄存器
TIM_ClearFlag(TIM5, TIM_FLAG_Update);
TIM_ITConfig(TIM5, TIM_IT_Update, ENABLE);
TIM_SetCounter(TIM5,0);
TIM_Cmd(TIM5, ENABLE); //启动TIM5定时器
}
/**************************************************************************
函数功能:单位时间读取编码器计数,此函数在定时器中断里面用我的是定时器6每隔5ms读取一次
入口参数:定时器
返回 值:计数值
**************************************************************************/
int x=0;
int Read_Encoder(u8 TIMX)
{
int Encoder_TIM;
switch(TIMX)
{
case 3: Encoder_TIM= (short)TIM3 -> CNT; TIM3 -> CNT=0;break;//
case 4: Encoder_TIM= (short)TIM4 -> CNT; TIM4 -> CNT=0;break;
case 5: Encoder_TIM= (short)TIM5 -> CNT; TIM5 -> CNT=0;break;
default: Encoder_TIM=0;
}
return Encoder_TIM;
}
初始化编码选择编码模式
TIM_EncoderInterfaceConfig(TIM5, TIM_EncoderMode_TI12, TIM_ICPolarity_BothEdge ,TIM_ICPolarity_BothEdge);主函数,距离可通过串口打印出来
int main(void)
{
uart_init(115200); //USART1_TX PA9 USART1_RX PA10
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //设置NVIC中断分组2:2位抢占优先级,2位响应优先级
delay_init();
MOTOR_Init(); //PC0,1 2 3
TIM6_Mode_Config_Init(); //使能定时器6 5ms中断一次
TIM4_Encoder_Init(); //使能TIM4对应的编码器 //PB6 PB7
TIM5_Encoder_Init(); //使能TIM5对应的编码器 //PA0 PA1
while(1)
{
;
}
}
void TIM6_IRQHandler(void) //定是时间不能太长否则计数器溢出了就会测量错误
{
if (TIM_GetITStatus(TIM6, TIM_IT_Update) != RESET)
{
danweilenth( Read_Encoder(4),Read_Encoder(5)); //每隔5ms中断一次 读取对应CNT的值,并计算路程
printf("Encoder.M1Lneth=%f\r\n",Encoder.M1Lneth);//打印出电机1的路程
printf("Encoder.M2Lneth=%f\r\n",Encoder.M2Lneth);//打印出电机2的路程
}
TIM_ClearITPendingBit(TIM6, TIM_IT_Update);
}
相关代码下面有下载可自行下:
两个编码器测距代码.7z
(191.89 KB, 下载次数: 25)
|