stm32霍尔编码器
程序员文章站
2022-06-11 15:54:32
...
霍尔编码器
想用一个定时器实现测速但是 TIM_Period ARR 过程中要读取cnt并置零 所以要两定时器
可用是stm32的霍尔编码功能;AB项那个上升沿先到判断cnt加减;
TIM_EncoderInterfaceConfig(TIM3,TIM_EncoderMode_TI12,
TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);检查全上升沿
无所谓方向问题实验一下就行了而且无法确认霍尔编码器那个的AB项(我菜我也不明白)
void Speed_Init(void)
{
GPIO_InitTypeDef GPIO_Struct;
TIM_TimeBaseInitTypeDef TIM_Base_Struct;
TIM_ICInitTypeDef TIM_IC_Struct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
GPIO_Struct.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Struct.GPIO_Pin = GPIO_Pin_6|GPIO_Pin_7;
GPIO_Init(GPIOA,&GPIO_Struct);
TIM_DeInit(TIM3);//预防
TIM_Base_Struct.TIM_Period = 6000;
TIM_Base_Struct.TIM_Prescaler = 0;
TIM_Base_Struct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_Base_Struct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_Base_Struct);
TIM_EncoderInterfaceConfig(TIM3,TIM_EncoderMode_TI12,
TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);//霍尔编码
TIM_IC_Struct.TIM_ICFilter = 9;
TIM_ICInit(TIM3, &TIM_IC_Struct);
TIM_Cmd(TIM3, ENABLE);
}
static void NVIC_Tim6_Init(void)
{
NVIC_InitTypeDef NVIC_Tim6_Struct;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
NVIC_Tim6_Struct.NVIC_IRQChannel = TIM6_IRQn;
NVIC_Tim6_Struct.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_Tim6_Struct.NVIC_IRQChannelSubPriority = 4;
NVIC_Tim6_Struct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_Tim6_Struct);
}
void TIM6_Init(void)
{
TIM_TimeBaseInitTypeDef TIM_Base_Struct;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM6,ENABLE);
TIM_DeInit(TIM6);//预防
TIM_Base_Struct.TIM_Period = 999;
TIM_Base_Struct.TIM_Prescaler = 71;//1ms
TIM_TimeBaseInit(TIM6, &TIM_Base_Struct);
TIM_ClearFlag(TIM6, TIM_FLAG_Update);
TIM_ITConfig(TIM6, TIM_IT_Update, ENABLE);
TIM_Cmd(TIM6, ENABLE);
NVIC_Tim6_Init();
}
利用ARR重装可以实现正负的判断极短的时间内计数不可能太高
#include "usart.h"
#include "tim_speed.h"
#include "delay.h"
int count = 0;
u16 time = 0;
float speed = 0;
int main (void)
{
Speed_Init();
USART_Config();
delay_init();
TIM6_Init();
while(1){
if(time == 500){
count = (short)TIM3 -> CNT;
TIM3 -> CNT=0;
if(time>5000){
speed = count/1540*3.1415*2*0.03/(time/1000);
printf("%5.3f\r\n",speed);
}else {
speed = (6000-count)/1540*3.1415*2*0.03/(time/1000);//由于电机年代久远搞不清楚减速比自己手动转一圈多次测试大概在1540
printf("-%5.3f\r\n",speed);
}
time = 0;
}
}
}
void TIM6_IRQHandler(void)
{
if ( TIM_GetITStatus( TIM6, TIM_IT_Update) != RESET ){
time++;
TIM_ClearITPendingBit(TIM6 , TIM_FLAG_Update);
}
}
学习中。。。。。仅作参考。