在这里使用TIM3的通道1和通道2做为A B项的电平捕捉。
由于STM32自带硬件编码器接口,因此只要设置好就可使用,非常强大,下面程序测试通过。
void TIM3_Mode_Config(void)
{
//u16 CCR1_Val = 2500;
//u16 CCR2_Val = 1000;
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_ICInitTypeDef TIM_ICInitStructure;
//TIM_OCInitTypeDef TIM_OCInitStructure;
/*----------------------------------------------------------------*/
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_StructInit(&GPIO_InitStructure);
/* Configure PA.06,07 as encoder input */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/*----------------------------------------------------------------*/
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); //使能TIM3
TIM_DeInit(TIM3);
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
TIM_TimeBaseStructure.TIM_Period =0xffff; //
TIM_TimeBaseStructure.TIM_Prescaler =0; //设置预分频:
TIM_TimeBaseStructure.TIM_ClockDivision =TIM_CKD_DIV1 ; //设置时钟分频系数:不分频
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数模式
//TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_CenterAligned1;
/*初始化TIM2定时器 */
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
/*-----------------------------------------------------------------*/
//编码配置 编码模式
TIM_EncoderInterfaceConfig(TIM3, TIM_EncoderMode_TI12,
TIM_ICPolarity_Rising, TIM_ICPolarity_Rising); //TIM_ICPolarity_Rising上升沿捕获
TIM_ICStructInit(&TIM_ICInitStructure);
TIM_ICInitStructure.TIM_ICFilter = 6; //比较滤波器
TIM_ICInit(TIM3, &TIM_ICInitStructure);
//TIM_ARRPreloadConfig(TIM3, ENABLE);
// Clear all pending interrupts
TIM_ClearFlag(TIM3, TIM_FLAG_Update);
TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE); //使能中断
//Reset counter
TIM3->CNT =0;
TIM_Cmd(TIM3, ENABLE); //使能定时器3
}
void TIM_Init(void)
{
TIM3_Mode_Config();
}
在主程序中通过串口定时发送。
[cpp] view plain copy
int main(void)
{
SystemInit();// 72m时钟
SysTick_Init();
TIM_Init();
NVIC_Config();
GPIO_74HC595_Config();
while (1)
{
encoder_num=TIM_GetCounter(TIM3);
// dis_595(encoder_num,encoder_num);
}
}
上一篇:STM32F107高级定时器TIM1使用 增量编码器接口配置
下一篇:STM32编码器的接口模式
推荐阅读最新更新时间:2024-03-16 16:14
- 热门资源推荐
- 热门放大器推荐