参照网上大神们写的增量式编码器,测量脉冲一直变
void Encoder_Init(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_ICInitTypeDef TIM_ICInitStructure;
/* Encoder unit connected to TIM3, 4X mode */
GPIO_InitTypeDef GPIO_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
/* TIM3 clock source enable */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
/* Enable GPIOA, clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
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;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* Enable the TIM3 Update Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = TIMx_PRE_EMPTION_PRIORITY;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = TIMx_SUB_PRIORITY;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
/* Timer configuration in Encoder mode */
TIM_DeInit(TIM3);
TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);
TIM_TimeBaseStructure.TIM_Prescaler = 0x0; // No prescaling
TIM_TimeBaseStructure.TIM_Period = (4*ENCODER_PPR)-1;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
TIM_EncoderInterfaceConfig(TIM3, TIM_EncoderMode_TI12,TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);
TIM_ICStructInit(&TIM_ICInitStructure);
TIM_ICInitStructure.TIM_ICFilter = ICx_FILTER;
TIM_ICInit(TIM3, &TIM_ICInitStructure);
// Clear all pending interrupts
TIM_ClearFlag(TIM3, TIM_FLAG_Update);
TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);
//Reset counter
TIM3->CNT = COUNTER_RESET;
//ENC_Clear_Speed_Buffer();
TIM_Cmd(TIM3, ENABLE);
}
void TIM3_IRQHandler(void)
{
/* Clear the interrupt pending flag */
TIM_ClearFlag(TIM3, TIM_FLAG_Update);
if (hEncoder_Timer_Overflow != U16_MAX)
{
hEncoder_Timer_Overflow++;
}
}
int main(void)
{
SystemInit();
delay_init(); //延时函数初始化
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);// 设置中断优先级分组2
uart_init(9600); //串口初始化为9600
TIM1_PWM_Init1(799,0);
LED_Init();
ADCInit();
Encoder_Init(); //PA6 PA7
while(1)
{
//Old_Count = Count; //获取先前的计数值
Count = TIM_GetCounter(TIM3); //获取编码器当前数值
printf("数值 = %d
",Count); //串口打印数值
Judge(); //转动电机
delay_ms(500);
}
}
我用的是16线的霍尔传感器(
https://item.taobao.com/item.htm ... amp;_u=h1lt4msm250f),电机匀速转动3s,每次测得的脉冲值都变化很大。图片中每次数值变化都是因为电机转了3s。为什么网上别的宝宝都能调试成功,就我不行
减速电机,手直接扭不动转不动哦。电机PWM我设置的是固定值
MSD0=(buff[5]-48)*100+(buff[6]-48)*10+(buff[7]-48);
PWM_SET1(1,MSD0);
delay_s(2);
PWM_SET1(0,0);
一周热门 更多>