编码器源码

decoder.c

#include "decoder.h"
#include <stm32f4xx_tim.h>
#include <stm32f4xx_gpio.h>
#include <stm32f4xx_rcc.h>
//开发者只需要调用Decoder_Init()进行初始化
//然后调用Decoder_GetCnt或者Decoder_GetSpeed获得数据即可
uint16_t con_speed_period=20;//20ms采集一次数据,根据实际修改
float Decoder_GetSpeed(void)
{
 static int16_t tmp;
 static float re_dat=0;
 tmp=(int16_t)Decoder_GetCnt();
  if(tmp>20000)tmp=20000;   //限幅
 else if(tmp<-20000)tmp=-20000;
 //编码器是1转输出256个正交脉冲,采用边缘计数,总共有256*4=1024
 //进行单位换算 
 re_dat=(float)(((int16_t)tmp)*1000/(1024.0*con_speed_period));
  return re_dat;
}
void Decoder_Init(void)
{
 Decoder_GPIO_Init();
 Decoder_TIM_Init();
}
void Decoder_GPIO_Init(void)
{
 GPIO_InitTypeDef GPIO_InitStructure;
   RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE , ENABLE);
  GPIO_InitStructure.GPIO_Pin =  GPIO_Pin_11|GPIO_Pin_9;
   GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
 GPIO_InitStructure.GPIO_OType = GPIO_OType_OD; 
 GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; 
   GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
   GPIO_Init(GPIOE, &GPIO_InitStructure);
    GPIO_PinAFConfig(GPIOE, GPIO_PinSource11, GPIO_AF_TIM1);
 GPIO_PinAFConfig(GPIOE, GPIO_PinSource9, GPIO_AF_TIM1);
}
void Decoder_TIM_Init(void)
{ 
 TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
 TIM_ICInitTypeDef TIM_ICInitStructure;

 RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1 , ENABLE); 

 TIM_DeInit(TIM1);
 TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);
 TIM_TimeBaseStructure.TIM_Period = ENCODER_TIM_PERIOD-1;
 TIM_TimeBaseStructure.TIM_Prescaler = 0x00;
 TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
 TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure); 
  TIM_EncoderInterfaceConfig(TIM1, TIM_EncoderMode_TI12, TIM_ICPolarity_Falling, TIM_ICPolarity_Falling);

 TIM_ICStructInit(&TIM_ICInitStructure);
 TIM_SetCounter(TIM1, 0);
 TIM_Cmd(TIM1, ENABLE);  
} 
//返回计数值
int Decoder_GetCnt()
{
 static int Decoder_cnt=0;
 Decoder_cnt=(short)(TIM1 -> CNT);
  TIM1 -> CNT=0; 
 return Decoder_cnt;
}
 

decoder.h

#ifndef _DECODER_H
#define _DECODER_H

#include “stm32f4xx.h”

#define ENCODER_TIM_PERIOD (u16)(65535) //不可大于65535

void Decoder_TIM_Init(void);
void Decoder_GPIO_Init(void);
void Decoder_Init(void);
int Decoder_GetCnt(void);
float Decoder_GetSpeed(void);

#endif

发布了6 篇原创文章 · 获赞 11 · 访问量 125

猜你喜欢

转载自blog.csdn.net/weixin_46156693/article/details/104455616