初始化
void Encoder_Init(void)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
//外设时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
//GPIO
GPIO_InitTypeDef GPIO_Init_Structure;
//看接在引脚的外部模块输出默认电平,
//若外部模块空闲默认输出高电平选择上拉输入默认输入高电平
//默认输出低电平配置下拉输入默认输入低电平
GPIO_Init_Structure.GPIO_Mode=GPIO_Mode_IPU;
GPIO_Init_Structure.GPIO_Pin=GPIO_Pin_6|GPIO_Pin_7;
GPIO_Init_Structure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_Init_Structure);
//不起作用,编码器接口会托管时钟,编码器接口就是一个带方向控制的外部时钟
//TIM_InternalClockConfig(TIM3); //内部时钟
//时基单元,让CNT在内部时钟的驱动下自增
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV1;
//不起作用,因为计数方向也被编码器接口托管
TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseInitStructure.TIM_Period=65536-1; //ARR
TIM_TimeBaseInitStructure.TIM_Prescaler=1-1;
TIM_TimeBaseInitStructure.TIM_RepetitionCounter=0;
TIM_TimeBaseInit(TIM3,&TIM_TimeBaseInitStructure);
TIM_ICInitTypeDef TIM_ICInitStruct;
//
TIM_ICStructInit(&TIM_ICInitStruct);
TIM_ICInitStruct.TIM_Channel=TIM_Channel_1;
TIM_ICInitStruct.TIM_ICFilter=0xF;
//编码器接口始终都是上升沿下降沿都有效,这里上升沿参数代表的是高低电平极性不反转,给下降沿就是反相
TIM_ICInitStruct.TIM_ICPolarity=TIM_ICPolarity_Rising;
// TIM_ICInitStruct.TIM_ICPrescaler=TIM_ICPSC_DIV1;
// TIM_ICInitStruct.TIM_ICSelection=TIM_ICSelection_DirectTI;
TIM_ICInit(TIM3,&TIM_ICInitStruct);
TIM_ICInitStruct.TIM_Channel=TIM_Channel_2;
TIM_ICInitStruct.TIM_ICFilter=0xF;
//TIM_ICInitStruct.TIM_ICPolarity=TIM_ICPolarity_Rising;
TIM_ICInit(TIM3,&TIM_ICInitStruct);
//Configures the TIMx Encoder Interface.
TIM_EncoderInterfaceConfig(TIM3,TIM_EncoderMode_TI12,TIM_ICPolarity_Rising,TIM_ICPolarity_Rising);
TIM_Cmd(TIM3,ENABLE);
}
int16_t Encoder_Get(void)
{
//每旋一次,cnt+4,说明有四个上升下降沿
int16_t temp;
temp=TIM_GetCounter(TIM3);
TIM_SetCounter(TIM3,0);
return temp;
}
主函数
可以通过Delay延时设置闸门和通过定时中断。一般选用定时中断闸门
int16_t speed;
int main(void)
{
OLED_Init();
Encoder_Init();
Timer_Init();
OLED_ShowString(1,1,"speed:");
while(1)
{
OLED_ShowSignedNum(2,5,speed,5);
//闸门
//Delay_ms(1000);
}
}
//中断每隔1s执行一次,可以修改中断时间来调整闸门时间
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM2,TIM_IT_Update)==SET)//这里用的是定时器的初始化部分不用修改TIM2
{
speed=Encoder_Get();
TIM_ClearITPendingBit(TIM2,TIM_IT_Update);
}
}