#include "encoding_disk.h"
#include "delay.h"
/**************************************************************************************
PA.6-> RUN-A2 TIM3-CH1//
PA.7-> RUN-B2 TIM3-CH2//
PB.0-> RUN-A1 TIM3-CH3//
PB.1-> RUN-B1 TIM3-CH4//
****************************************************************************************/
#define ENCODER_TIMER TIM3 // Encoder unit connected to TIM3
#define ENCODER_PPR (u16)(100) // number of pulses per revolution
#define SPEED_BUFFER_SIZE 8
#define COUNTER_RESET (u16)0
#define ICx_FILTER (u8) 6 // 6<-> 670nsec
#define TIMx_PRE_EMPTION_PRIORITY 1
#define TIMx_SUB_PRIORITY 0
#define ENCODER_TIM_PERIOD 0xffff//
#define MAX_COUNT 10000//
void EncodingDisk_Init(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_ICInitTypeDef TIM_ICInitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);//
/* Enable GPIOA, clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);//??GPIOA??
GPIO_StructInit(&GPIO_InitStructure);
/* Configure PA.06,07 as encoder input */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//PA8 PA9????
GPIO_Init(GPIOA, &GPIO_InitStructure);
TIM_DeInit(ENCODER_TIMER);
TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);
TIM_TimeBaseStructure.TIM_Prescaler = 0x0; // No prescaling //??????????0,???
//TIM_TimeBaseStructure.TIM_Period = (4*ENCODER_PPR)-1; //????????
TIM_TimeBaseStructure.TIM_Period = ENCODER_TIM_PERIOD-1;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;//?????? T_dts = T_ck_int
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM????
TIM_TimeBaseInit(ENCODER_TIMER, &TIM_TimeBaseStructure);
TIM_EncoderInterfaceConfig(ENCODER_TIMER, TIM_EncoderMode_TI12,TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);/
TIM_ICStructInit(&TIM_ICInitStructure);
TIM_ICInitStructure.TIM_ICFilter =ICx_FILTER;
TIM_ICInit(ENCODER_TIMER, &TIM_ICInitStructure);
TIM_ClearFlag(ENCODER_TIMER, TIM_FLAG_Update);//??TIM1??????
TIM_ITConfig(ENCODER_TIMER, TIM_IT_Update, ENABLE);
TIM3->CNT = 0;
TIM_Cmd(ENCODER_TIMER, ENABLE);
}
s16 Enc_GetCount(void)
{
static u16 lastCount = 0;
u16 curCount = ENCODER_TIMER->CNT;
s32 dAngle = curCount - lastCount;
if(dAngle >= MAX_COUNT)
{
dAngle -= ENCODER_TIM_PERIOD;
}
else if(dAngle < -MAX_COUNT)
{
dAngle += ENCODER_TIM_PERIOD;
}
lastCount = curCount;
return (s16)dAngle;
}
主函数通过
int main(void)
{
s16 temp,NUM;
delay_init();
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
EncodingDisk_Init();
Usart_Init(9600);
GPIO_SetBits (GPIOA,GPIO_Pin_11);
while(1)
{
NUM = TIM_GetCounter(TIM3)/2;
if(NUM!=temp)
{
temp=NUM;
printf("%d\r\n",NUM);
}
delay_ms(300);
}
紧急求助,单片机内部测正交编码的,是不是必须得是正交编码的电平,它才能出来值?