81 lines
2.2 KiB
C
81 lines
2.2 KiB
C
|
#include "stm32f10x.h" // Device header
|
||
|
|
||
|
int16_t Encoder_Count;
|
||
|
|
||
|
void Encoder_Init(void)
|
||
|
{
|
||
|
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
|
||
|
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
|
||
|
|
||
|
GPIO_InitTypeDef GPIO_InitStructure;
|
||
|
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
|
||
|
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4 | GPIO_Pin_5;
|
||
|
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
|
||
|
GPIO_Init(GPIOA, &GPIO_InitStructure);
|
||
|
|
||
|
GPIO_EXTILineConfig(GPIO_PortSourceGPIOA, GPIO_PinSource4);
|
||
|
GPIO_EXTILineConfig(GPIO_PortSourceGPIOA, GPIO_PinSource5);
|
||
|
|
||
|
EXTI_InitTypeDef EXTI_InitStructure;
|
||
|
EXTI_InitStructure.EXTI_Line = EXTI_Line4 | EXTI_Line5;
|
||
|
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
|
||
|
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
|
||
|
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
|
||
|
EXTI_Init(&EXTI_InitStructure);
|
||
|
|
||
|
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
|
||
|
|
||
|
NVIC_InitTypeDef NVIC_InitStructure;
|
||
|
NVIC_InitStructure.NVIC_IRQChannel = EXTI4_IRQn;
|
||
|
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
|
||
|
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
|
||
|
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
|
||
|
NVIC_Init(&NVIC_InitStructure);
|
||
|
|
||
|
NVIC_InitStructure.NVIC_IRQChannel = EXTI9_5_IRQn;
|
||
|
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
|
||
|
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
|
||
|
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
|
||
|
NVIC_Init(&NVIC_InitStructure);
|
||
|
}
|
||
|
|
||
|
int16_t Encoder_Get(void)
|
||
|
{
|
||
|
int16_t Temp;
|
||
|
Temp = Encoder_Count;
|
||
|
Encoder_Count = 0;
|
||
|
return Temp;
|
||
|
}
|
||
|
|
||
|
void EXTI4_IRQHandler(void)
|
||
|
{
|
||
|
if (EXTI_GetITStatus(EXTI_Line4) == SET)
|
||
|
{
|
||
|
/*如果出现数据乱跳的现象,可再次判断引脚电平,以避免抖动*/
|
||
|
if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_4) == 0)
|
||
|
{
|
||
|
if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_5) == 0)
|
||
|
{
|
||
|
Encoder_Count --;
|
||
|
}
|
||
|
}
|
||
|
EXTI_ClearITPendingBit(EXTI_Line4);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
void EXTI9_5_IRQHandler(void)
|
||
|
{
|
||
|
if (EXTI_GetITStatus(EXTI_Line5) == SET)
|
||
|
{
|
||
|
/*如果出现数据乱跳的现象,可再次判断引脚电平,以避免抖动*/
|
||
|
if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_5) == 0)
|
||
|
{
|
||
|
if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_4) == 0)
|
||
|
{
|
||
|
Encoder_Count ++;
|
||
|
}
|
||
|
}
|
||
|
EXTI_ClearITPendingBit(EXTI_Line5);
|
||
|
}
|
||
|
}
|