#include "encode.h"
#define ENCODER_TIM_PERIOD 38500 //编码器转一圈产生的脉冲数
//配置编码器端口
void Encode_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);//使能GPIOB时钟
GPIO_StructInit(&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
// TIM1中断优先级配置
void TIM4_NVIC_Configuration(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
NVIC_InitStructure.NVIC_IRQChannel = TIM4_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void TIM4_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_ICInitTypeDef TIM_ICInitStructure;
//时钟源
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
TIM_DeInit(TIM1);
TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);
TIM_TimeBaseStructure.TIM_Prescaler = 0x0;
//TIM_TimeBaseStructure.TIM_Period = (4*ENCODER_PPR)-1; //设置自动重装载值
TIM_TimeBaseStructure.TIM_Period = ENCODER_TIM_PERIOD-1;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);
//编码器接口配置
TIM_EncoderInterfaceConfig(TIM4, TIM_EncoderMode_TI12,
TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);
TIM_ICStructInit(&TIM_ICInitStructure); //设置缺省默认值
TIM_ICInitStructure.TIM_ICFilter =6;
//选择输入比较滤波器初始化
TIM_ICInit(TIM4, &TIM_ICInitStructure);
// Clear all pending interrupts
TIM_ClearFlag(TIM4, TIM_FLAG_Update);
TIM_ITConfig(TIM4, TIM_IT_Update, ENABLE);
// TIM1->CNT =0;
//CurrentCount = TIM1->CNT;
TIM_Cmd(TIM4, ENABLE);
}
void Encode_Init(void)
{
Encode_GPIO_Config();
TIM4_NVIC_Configuration();
TIM4_Configuration();
}
/*********************************************END OF FILE**********************/
主函数部分
while(1)
{
if ( time == 20 ) /* 1000 * 1 ms = 1s ʱ¼äµ½ */
{
time = 0;
temp=TIM_GetCounter(TIM4);
__NOP();
}
}
}
中断部分
/*********************************************END OF FILE**********************/
void TIM4_IRQHandler(void)
{
if(TIM_GetITStatus(TIM4, TIM_IT_Update) == SET)
{
TIM_ClearITPendingBit(TIM4,TIM_IT_Update);
if(1==((TIM4->CR1)&0x0010)>>4)
{
Direction--;
__NOP();
}
if(0==((TIM4->CR1)&0x0010)>>4)
{
Direction++;
__NOP();
}
}
}
|