话不多说,先上效果图看下先 图中可看到正转和反转之间没有任何一个干扰信号
STM32输入捕获初始化配置程序 因为检测原理和中断输入一样,所以也可设为中断输入
#include "timer.h"
#include "usart.h"
#include "delay.h"
#define CLK PAin(0)
#define DT PAin(1)
void TIM5_Cap_Init(u16 arr,u16 psc)
{
TIM_ICInitTypeDef TIM5_ICInitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0|GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
TIM_TimeBaseStructure.TIM_Period = arr;
TIM_TimeBaseStructure.TIM_Prescaler =psc;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM5, &TIM_TimeBaseStructure);
TIM5_ICInitStructure.TIM_Channel = TIM_Channel_1;
TIM5_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
TIM5_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
TIM5_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
TIM5_ICInitStructure.TIM_ICFilter = 0x00;
TIM_ICInit(TIM5, &TIM5_ICInitStructure);
NVIC_InitStructure.NVIC_IRQChannel = TIM5_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_ITConfig(TIM5,TIM_IT_CC1,ENABLE);
TIM_Cmd(TIM5,ENABLE );
TIM_OC1PolarityConfig(TIM5,TIM_ICPolarity_Falling);
}
旋转编码器的定时器中断处理程序
_Bool TIM5CH1_CAPTURE_STA=0;
_Bool bit=0;
_Bool dt=0;
u8 state=0;
u16 num=0;
void TIM5_IRQHandler(void)
{
if(TIM_GetITStatus(TIM5, TIM_IT_CC1) != RESET)
{
if(TIM5CH1_CAPTURE_STA==0)
{
dt=DT;
if(CLK==0){
delay_ms(1);
if(CLK==0){
if(dt)
state=2;
else
state=1;
TIM5CH1_CAPTURE_STA=1;
TIM_OC1PolarityConfig(TIM5,TIM_ICPolarity_Rising);
}
}
}
if(TIM5CH1_CAPTURE_STA==1)
{
dt=DT;
if(CLK==1){
delay_us(300);
if(CLK==1){
if((dt==0) && (state==2)){
state=4;
num++;
bit=1;
}
else if((dt==1) && (state==1)){
num--;
state=3;
bit=1;
}
TIM5CH1_CAPTURE_STA=0;
TIM_OC1PolarityConfig(TIM5,TIM_ICPolarity_Falling);
}
}
}
}
TIM_ClearITPendingBit(TIM5, TIM_IT_CC1);
}
_Bool是C99中支持的布尔变量类型
|