编码器正交解码 STM32F4
作者:互联网
原理:
- 当计数值向上溢出或者向下溢出时,对应增加和减少重装载的值 0xFFFF。
- 对此读取 (TIM1->CNT + abs_count)是为了防止中途被中断打断而破坏组包数据。不建议屏蔽中断去读取,查询过快时也会造成中断开启关闭过快,会造成系统实时性下降。
static int abs_count = 0;//绝对位置
void Speed_ENC(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_11;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOE, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOE, GPIO_PinSource9, GPIO_AF_TIM1);
GPIO_PinAFConfig(GPIOE, GPIO_PinSource11, GPIO_AF_TIM1);
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
TIM_EncoderInterfaceConfig(TIM1, TIM_EncoderMode_TI12, TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);
TIM_Cmd(TIM1, ENABLE);
NVIC_InitStructure.NVIC_IRQChannel = TIM1_UP_TIM10_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_ClearITPendingBit(TIM1, TIM_IT_Update);
TIM_ITConfig(TIM1, TIM_IT_Update, ENABLE);
}
void TIM1_UP_TIM10_IRQHandler(void)
{
if (TIM_GetITStatus(TIM1, TIM_IT_Update) != RESET) //溢出
{
if (TIM1->CR1 & (1 << 4))
abs_count -= 0xFFFF;
else
abs_count += 0xFFFF;
TIM_ClearITPendingBit(TIM1, TIM_IT_Update);
}
}
//***************设置当前绝对位置**************
void TIM1_Encoder_Write(int data)
{
TIM_ITConfig(TIM1, TIM_IT_Update, DISABLE);
TIM1->CNT = 0;
abs_count = data;
TIM_ClearITPendingBit(TIM1, TIM_IT_Update);
TIM_ITConfig(TIM1, TIM_IT_Update, ENABLE);
}
//*************读计当前绝对位置**************
int TIM1_Encoder_Read(void)
{
int cnt1 = TIM1->CNT + abs_count;
int cnt2 = TIM1->CNT + abs_count;
if (cnt1 == cnt2)
return cnt1; //未出现中断
else
return TIM1->CNT + abs_count; //可能刚发生中断
}
标签:编码器,TIM1,解码,NVIC,TIM,ENABLE,InitStructure,STM32F4,GPIO 来源: https://blog.csdn.net/ai5945fei/article/details/104700854