编码器程序:
电机选取加速比为1:30。编码器线数为11。
轮胎转一圈产生30x11个脉冲,单片机编码器计数器计数为30x11x4。
电机速度为电机脉冲值x单片机编码器计数器计数。
/* USER CODE BEGIN PTD */
#define ABS(X) (X>0) ? (X=X) : (X=-X)
#define IN4(H) if(H)\
HAL_GPIO_WritePin(IN4_GPIO_Port,IN4_Pin,GPIO_PIN_SET);\
else HAL_GPIO_WritePin(IN4_GPIO_Port,IN4_Pin, GPIO_PIN_RESET);
#define IN3(H) if(H)\
HAL_GPIO_WritePin(IN3_GPIO_Port,IN3_Pin,GPIO_PIN_SET);\
else HAL_GPIO_WritePin(IN3_GPIO_Port,IN3_Pin, GPIO_PIN_RESET);
#define IN2(H) if(H)\
HAL_GPIO_WritePin(IN2_GPIO_Port,IN2_Pin,GPIO_PIN_SET);\
else HAL_GPIO_WritePin(IN2_GPIO_Port,IN2_Pin, GPIO_PIN_RESET);
#define IN1(H) if(H)\
HAL_GPIO_WritePin(IN1_GPIO_Port,IN1_Pin,GPIO_PIN_SET);\
else HAL_GPIO_WritePin(IN1_GPIO_Port,IN1_Pin, GPIO_PIN_RESET);
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
int32_t Encoder1Count = 0;
int32_t Encoder2Count = 0;
int64_t total_EncCount1 = 0;
int64_t total_EncCount2 = 0;
float Motor1Speed = 0.0;
float Motor2Speed = 0.0;
uint32_t uwtick_8ms_delay = 0;
/* USER CODE END PM */
/***********************************************************************************************
函 数 名:void Get_Encoder(void)
功 能:
说 明:获取编码器反馈 8ms采样
************************************************************************************************/
void Get_Encoder(void) //获取编码器反馈
{
Encoder1Count = - (short)__HAL_TIM_GetCounter(&htim2);//获取电机脉冲值
Encoder2Count = - (short)__HAL_TIM_GetCounter(&htim4);//获取电机脉冲值
total_EncCount1 += Encoder1Count; //位置累加
total_EncCount2 += Encoder2Count;
__HAL_TIM_SetCounter(&htim2,0); //清除编码器值
__HAL_TIM_SetCounter(&htim4,0); //清除编码器值
Motor1Speed = (float)Encoder1Count*100/30.0/11/4;//计算速度
Motor2Speed = (float)Encoder2Count*100/30.0/11/4;
}
/**************************************************************************
函 数 名:void set_speed(int16_t left_speed,int16_t right_speed)
功 能:速度设定函数
入口参数:左右轮速度
**************************************************************************/
void set_speed(int16_t left_speed,int16_t right_speed)//设定电机转速
{
if(left_speed>0) {IN1(1);IN2(0);}
else {IN1(0);IN2(1);}
if(right_speed>0) {IN3(0);IN4(1);}
else {IN3(1);IN4(0);}
__HAL_TIM_SetCompare(&htim1, TIM_CHANNEL_1, ABS(left_speed));
__HAL_TIM_SetCompare(&htim1, TIM_CHANNEL_4, ABS(right_speed));
}
|