读取编码器数值实现电机测速
电机系列
二、读取编码器数值实现电机测速
3、速度;
测速原理:
单位时间内,根据脉冲走过的距离计算电机实际速度,这里采用5ms定时器中断。
采集数据:
就是获得到轮子转一圈的编码器个数;
注意电机参数:
减速比:30:1
编码器线数:13线,也称编码器分辨率;
使用四倍频提高测量精度;
代码见下载区。
速度计算思路:

单位时间内获得的编码器脉冲变化数:可以通过代码得到,定为 e 个 ; (反应电机正反转)
单位时间:定时器设定为5ms,即0.005s;
电机转动一圈的脉冲数:n 个
电机轮子半径:R 单位:m(米)
圆周率:PI 单位:无
速度:speed 单位: m/s

此处:
轮子半径 R:0.03m(米);
PI:3.1415926;
手动转一圈的脉冲数 n:1560 个;
e: 通过函数得到;
可得:
speed = 0.024166 * e
代码:
结构如下:

encoder.h
将2中部分改为一下代码;
#ifndef __ENCODER_H
#define __ENCODER_H
#include <sys.h>
#include "stm32f10x_tim.h"
/**************************************************************************
作者:chance
**************************************************************************/
#define ENCODER_TIM_PERIOD (u16)(65535) //不可大于65535 因为F103的定时器是16位的。
//定时器编码器初始化;
void Encoder_Init_TIM2(u16 arr,u16 psc);
void Encoder_Init_TIM3(u16 arr,u16 psc);
void Encoder_Init_TIM4(u16 arr,u16 psc);
void Encoder_Init_TIM5(u16 arr,u16 psc);
//5ms 定时器中断服务函数
void TIM7_Int_Init(u16 arr,u16 psc);
//编码器计数函数;
int Read_Encoder_TIM2(void);
int Read_Encoder_TIM3(void);
int Read_Encoder_TIM4(void);
int Read_Encoder_TIM5(void);
int Read_Encoder_test(TIM_TypeDef * TIMx);
//speed
void Get_Motor_Speed(int *A_Speed,int *B_Speed,int *C_Speed,int *D_Speed);
#endif
encoder.c
#include "encoder.h"
#include "stm32f10x_gpio.h"
/**************************************************************************
作者:chance
**************************************************************************/
int Encoder_A,Encoder_B,Encoder_C,Encoder_D; //编码器的脉冲计数
void Encoder_Init_TIM2(u16 arr,u16 psc)
{
//1) 定义相关结构体:
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_ICInitTypeDef TIM_ICInitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
//2) 使能相关时钟:
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);// 需要使能AFIO时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);//使能定时器2的时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);//使能PA端口时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);//使能PB端口时钟
GPIO_PinRemapConfig(GPIO_FullRemap_TIM2, ENABLE);
GPIO_PinRemapConfig(GPIO_Remap_SWJ_JTAGDisable , ENABLE); //禁止JTAG功能,把PB3,PB4作为普通IO口使用
//3) 初始化 GPIO:(用于AB相,脉冲计数)
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15; //端口配置
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //浮空输入
GPIO_Init(GPIOA, &GPIO_InitStructure); //根据设定参数初始化GPIOA
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3; //端口配置
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //浮空输入
GPIO_Init(GPIOB, &GPIO_InitStructure); //根据设定参数初始化GPIOB
//4) 设置并初始化定时器 TIM2:
TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);
TIM_TimeBaseStructure.TIM_Prescaler = psc; // 预分频器
TIM_TimeBaseStructure.TIM_Period = arr; //设定计数器自动重装值
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;//选择时钟分频:不分频
TIM_TimeBaseStructure

该博客聚焦电机测速,介绍通过读取编码器数值实现测速的方法。阐述了测速原理,即利用5ms定时器中断,根据单位时间脉冲走过距离计算速度。说明了采集数据要点,如获取轮子转一圈编码器个数等,还给出速度计算思路及公式,最后提及相关代码结构及查看速度的方式。
最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



