STM32F407 步进电机匀速圆形插补

31 篇文章 4 订阅
/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2022 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

#include "bsp_delay.h"
#include "bsp_key.h"
#include "bsp_motor.h"

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
TIM_HandleTypeDef htim8;

UART_HandleTypeDef huart1;

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_TIM8_Init(void);
static void MX_USART1_UART_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_TIM8_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */
	
	delay_init(168);
	
	HAL_GPIO_WritePin(GPIOD, GPIO_PIN_3, GPIO_PIN_RESET);		/* 设置方向 */
	HAL_GPIO_WritePin(GPIOD, GPIO_PIN_7, GPIO_PIN_RESET);	/* 使能ENABLE */
	
	g_motor_state = MOTOR_STOP;
	
	uint32_t tick_start_run;	/* 开始运行时刻 */
	uint32_t tick;
	uint8_t buffer_usart_send[16];
	uint8_t i;
	uint16_t sum;
	
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
		if(KEY1_StateRead() == KEY_DOWN)
    {
			motor_circle_interpolation(100, 20);
			tick_start_run = HAL_GetTick();
    }
		if (KEY2_StateRead() == KEY_DOWN)
		{
			motor_circle_interpolation(-100, 20);
			tick_start_run = HAL_GetTick();
		}
		
		tick = HAL_GetTick();
		
		buffer_usart_send[0] = 0x01;															/* 帧头 */
		buffer_usart_send[1] = 0x67;															/* 帧头 */	
		buffer_usart_send[2] = 0x42;															/* 帧头 */
		buffer_usart_send[3] = 0xc0;															/* 帧头 */
		buffer_usart_send[4] = (tick - tick_start_run) >> 8;			/* 时刻 */
		buffer_usart_send[5] = (tick - tick_start_run) & 0xff;		/* 时刻 */
		buffer_usart_send[6] = g_rel_position_x >> 24;							/* 电机运行一步需要定时器的脉冲数 */
		buffer_usart_send[7] = g_rel_position_x >> 16;							/* 电机运行一步需要定时器的脉冲数 */
		buffer_usart_send[8] = g_rel_position_x >> 8;								/* 电机运行一步需要定时器的脉冲数 */
		buffer_usart_send[9] = g_rel_position_x & 0xff;							/* 电机运行一步需要定时器的脉冲数 */
		buffer_usart_send[10] = g_rel_position_y >> 24;							/* 电机已经运行的步数 */
		buffer_usart_send[11] = g_rel_position_y >> 16;							/* 电机已经运行的步数 */
		buffer_usart_send[12] = g_rel_position_y >> 8;							/* 电机已经运行的步数 */
		buffer_usart_send[13] = g_rel_position_y & 0xff;						/* 电机已经运行的步数 */
		
		sum = 0;
		for (i = 4; i < 14; i++)
		{
			sum += buffer_usart_send[i];
		}
		buffer_usart_send[14] = sum >> 8;
		buffer_usart_send[15] = sum & 0xff;
		
		HAL_UART_Transmit(&huart1, buffer_usart_send, 16, 1000);
		
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 8;
  RCC_OscInitStruct.PLL.PLLN = 336;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 4;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief TIM8 Initialization Function
  * @param None
  * @retval None
  */
static void MX_TIM8_Init(void)
{

  /* USER CODE BEGIN TIM8_Init 0 */

  /* USER CODE END TIM8_Init 0 */

  TIM_ClockConfigTypeDef sClockSourceConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};
  TIM_OC_InitTypeDef sConfigOC = {0};
  TIM_BreakDeadTimeConfigTypeDef sBreakDeadTimeConfig = {0};

  /* USER CODE BEGIN TIM8_Init 1 */

  /* USER CODE END TIM8_Init 1 */
  htim8.Instance = TIM8;
  htim8.Init.Prescaler = 20;
  htim8.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim8.Init.Period = 65535;
  htim8.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim8.Init.RepetitionCounter = 0;
  htim8.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim8) != HAL_OK)
  {
    Error_Handler();
  }
  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim8, &sClockSourceConfig) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_TIM_PWM_Init(&htim8) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_TIM_OnePulse_Init(&htim8, TIM_OPMODE_SINGLE) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim8, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigOC.OCMode = TIM_OCMODE_PWM1;
  sConfigOC.Pulse = 65535;
  sConfigOC.OCPolarity = TIM_OCPOLARITY_LOW;
  sConfigOC.OCNPolarity = TIM_OCNPOLARITY_HIGH;
  sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
  sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET;
  sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET;
  if (HAL_TIM_PWM_ConfigChannel(&htim8, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
  {
    Error_Handler();
  }
  __HAL_TIM_DISABLE_OCxPRELOAD(&htim8, TIM_CHANNEL_1);
  sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
  if (HAL_TIM_PWM_ConfigChannel(&htim8, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
  {
    Error_Handler();
  }
  __HAL_TIM_DISABLE_OCxPRELOAD(&htim8, TIM_CHANNEL_2);
  sBreakDeadTimeConfig.OffStateRunMode = TIM_OSSR_DISABLE;
  sBreakDeadTimeConfig.OffStateIDLEMode = TIM_OSSI_DISABLE;
  sBreakDeadTimeConfig.LockLevel = TIM_LOCKLEVEL_OFF;
  sBreakDeadTimeConfig.DeadTime = 0;
  sBreakDeadTimeConfig.BreakState = TIM_BREAK_DISABLE;
  sBreakDeadTimeConfig.BreakPolarity = TIM_BREAKPOLARITY_HIGH;
  sBreakDeadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE;
  if (HAL_TIMEx_ConfigBreakDeadTime(&htim8, &sBreakDeadTimeConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM8_Init 2 */
	
	__HAL_TIM_ENABLE_IT(&htim8, TIM_IT_UPDATE);

  /* USER CODE END TIM8_Init 2 */
  HAL_TIM_MspPostInit(&htim8);

}

/**
  * @brief USART1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART1_UART_Init(void)
{

  /* USER CODE BEGIN USART1_Init 0 */

  /* USER CODE END USART1_Init 0 */

  /* USER CODE BEGIN USART1_Init 1 */

  /* USER CODE END USART1_Init 1 */
  huart1.Instance = USART1;
  huart1.Init.BaudRate = 115200;
  huart1.Init.WordLength = UART_WORDLENGTH_8B;
  huart1.Init.StopBits = UART_STOPBITS_1;
  huart1.Init.Parity = UART_PARITY_NONE;
  huart1.Init.Mode = UART_MODE_TX_RX;
  huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart1.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART1_Init 2 */

  /* USER CODE END USART1_Init 2 */

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOE_CLK_ENABLE();
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOH_CLK_ENABLE();
  __HAL_RCC_GPIOF_CLK_ENABLE();
  __HAL_RCC_GPIOD_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();
  __HAL_RCC_GPIOI_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOF, GPIO_PIN_11, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOD, GPIO_PIN_11|GPIO_PIN_3|GPIO_PIN_7, GPIO_PIN_RESET);

  /*Configure GPIO pins : PE2 PE3 PE4 PE0
                           PE1 */
  GPIO_InitStruct.Pin = GPIO_PIN_2|GPIO_PIN_3|GPIO_PIN_4|GPIO_PIN_0
                          |GPIO_PIN_1;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);

  /*Configure GPIO pin : PF11 */
  GPIO_InitStruct.Pin = GPIO_PIN_11;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
  HAL_GPIO_Init(GPIOF, &GPIO_InitStruct);

  /*Configure GPIO pins : PD11 PD3 PD7 */
  GPIO_InitStruct.Pin = GPIO_PIN_11|GPIO_PIN_3|GPIO_PIN_7;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
  HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);

}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

#ifndef BSP_MOTOR_H
#define BSP_MOTOR_H

#include "main.h"

#ifdef __cplusplus
extern "C" {
#endif

#define MOTOR_LEAD	40															/* 电机模组导程,单位0.1mm */
#define STEP_PER_CIRCLE	200													/* 细分为1时,电机走一圈需要的步数 */
#define MOTOR_DRIVER_SUBDIVISION	32								/*电机驱动器细分*/
#define TIM_CLK	8000000														/* 定时器时钟频率 */
#define TIM_ARR_MAX	65535

#define MOTOR_X_DIR_FORWARD \
  do { \
		HAL_GPIO_WritePin(GPIOD, GPIO_PIN_3, GPIO_PIN_RESET); \
  } while(0)
	
#define MOTOR_X_DIR_REVERSE \
  do { \
		HAL_GPIO_WritePin(GPIOD, GPIO_PIN_3, GPIO_PIN_SET); \
  } while(0)
	
#define MOTOR_X_ENABLE \
  do { \
		HAL_GPIO_WritePin(GPIOD, GPIO_PIN_7, GPIO_PIN_RESET); \
  } while(0)
	
#define MOTOR_X_DISABLE \
  do { \
		HAL_GPIO_WritePin(GPIOD, GPIO_PIN_7, GPIO_PIN_SET); \
  } while(0)
	
#define MOTOR_Y_DIR_FORWARD \
  do { \
		HAL_GPIO_WritePin(GPIOD, GPIO_PIN_11, GPIO_PIN_RESET); \
  } while(0)
	
#define MOTOR_Y_DIR_REVERSE \
  do { \
		HAL_GPIO_WritePin(GPIOD, GPIO_PIN_11, GPIO_PIN_SET); \
  } while(0)
	
#define MOTOR_Y_ENABLE \
  do { \
		HAL_GPIO_WritePin(GPIOF, GPIO_PIN_11, GPIO_PIN_RESET); \
  } while(0)
	
#define MOTOR_Y_DISABLE \
  do { \
		HAL_GPIO_WritePin(GPIOF, GPIO_PIN_11, GPIO_PIN_SET); \
  } while(0)

typedef enum
{
	MOTOR_STOP = 0,
	MOTOR_ACCELERATE,
	MOTOR_UNIFORM,
	MOTOR_DECELERATE
}motor_run_state_typedef;

typedef enum
{
	MOTOR_FORWARD = 0,
	MOTOR_REVERSE
}motor_dir_typedef;

typedef enum
{
	CIRCLE_CLOCKWISE = 0,
	CIRCLE_COUNTERCLOCKWISE
}circle_dir_typedef;

typedef enum
{
	MOTOR_X = 0,
	MOTOR_Y
}motor_name_typedef;

typedef enum
{
  FIRST_QUADRANT = 0,
  SECOND_QUADRANT,
	THIRD_QUADRANT,
	FOURTH_QUADRANT
}quadrant_typedef;

// 插补算法类型定义
typedef struct {
  __IO circle_dir_typedef inter_dir;    	/* 插补方向 */
  __IO quadrant_typedef qua_points;   							/* 象限点 */
  __IO uint8_t x_dir;        							/* X轴方向 */
  __IO uint8_t y_dir;        							/* Y轴方向 */
  __IO int32_t end_x;		 	  							/* 终点坐标X */
	__IO int32_t end_y;		 	  							/* 终点坐标Y */
	__IO uint32_t end_pulse;	  						/* 终点位置总的脉冲数 */
	__IO motor_name_typedef active_axis;  						/* 活动轴 */
	__IO int32_t f_e;			 	  							/* 函数方程 */
}interpolation_typedef;

extern motor_run_state_typedef g_motor_state;		
extern motor_dir_typedef motor_x_dir, motor_y_dir;
extern uint32_t g_steps_total;
extern uint32_t g_step_timer_pulse_num;
extern uint32_t g_step_timer_pulse_num_min;			
extern uint32_t g_steps_radius;

extern interpolation_typedef g_circle;
extern __IO int32_t g_rel_position_x;         
extern __IO int32_t g_rel_position_y;      
extern __IO uint32_t g_steps_done_x;							
extern __IO uint32_t g_steps_done_y;					

extern uint32_t g_motor_s_shape_acceleration_step;				

uint8_t motor_circle_interpolation(int32_t radius, uint32_t speed);
uint8_t circle_inc_move(uint32_t radius_step, circle_dir_typedef dir, quadrant_typedef quadrant);

#ifdef __cplusplus
}
#endif

#endif /* BSP_MOTOR_H */



#include "bsp_motor.h"
#include <math.h>

/**
* 电机运行状态
*	在main函数中会引用到
*	每当电机为运行状态时下位机通过串口将电机状态发送给上位机
*/
motor_run_state_typedef g_motor_state;

motor_dir_typedef motor_x_dir, motor_y_dir;				/* 电机运行方向 */

uint32_t g_steps_total;													/* 电机总共需要运行的步数 */
uint32_t g_step_timer_pulse_num;									/* 电机运行一步需要定时器的脉冲数 */
uint32_t g_step_timer_pulse_num_min;							/* 电机运行一步需要定时器的脉冲数的最小值 */
uint32_t g_steps_radius;													/* 圆半径,单位:步 */

interpolation_typedef g_circle;
__IO int32_t g_rel_position_x;            				/* 当前位置  单位:脉冲数 */ 
__IO int32_t g_rel_position_y;            				/* 当前位置  单位:脉冲数 */
__IO uint32_t g_steps_done_x;											/* 已经运行的步数  单位:脉冲数 */ 
__IO uint32_t g_steps_done_y;											/* 已经运行的步数  单位:脉冲数 */ 

uint32_t g_motor_s_shape_acceleration_step;				/* 电机总共需要运行的步数 */

/**
* @brief 电机圆形运行
* @param	radius:圆形半径,单位:0.1mm,有符号数,正表示方向顺时针,负数表示方向逆时针
* @param	speed:匀速运行的速度,单位:0.1mm/s
* @note: 
* @retval 0:执行成功
*/
uint8_t motor_circle_interpolation(int32_t radius, uint32_t speed)
{
	if (radius > 0)
	{
		g_circle.inter_dir = CIRCLE_CLOCKWISE;
	}
	else if (radius < 0)
	{
		g_circle.inter_dir = CIRCLE_COUNTERCLOCKWISE;
		radius = 0 - radius;
	}
	else	/* radius == 0,参数有问题 */
	{
		return 1;
	}
	
	g_steps_radius = radius * STEP_PER_CIRCLE * MOTOR_DRIVER_SUBDIVISION / MOTOR_LEAD;	/* 将距离转换为步数 */ 
	g_step_timer_pulse_num = TIM_CLK * MOTOR_LEAD * 1.0 / speed / STEP_PER_CIRCLE / MOTOR_DRIVER_SUBDIVISION;
	g_steps_total = g_steps_radius * 8;
	g_steps_done_x = 0;
	g_steps_done_y = 0;
	
	if (g_circle.inter_dir == CIRCLE_CLOCKWISE)
	{
		g_circle.qua_points = FOURTH_QUADRANT;
	}
	else if (g_circle.inter_dir == CIRCLE_COUNTERCLOCKWISE)
	{
		g_circle.qua_points = FIRST_QUADRANT;
	}
	else
	{
		return 1;
	}
	
	circle_inc_move(g_steps_radius, g_circle.inter_dir, g_circle.qua_points);
	
	g_motor_state = MOTOR_UNIFORM;
	
	return 0;
}

/**
* @brief 圆形插补增量运动,从当前坐标(step,0)围绕(0,0)走一圈
* @param	radius_step:半径,单位:步
* @param	dir:方向,取值:CIRCLE_CLOCKWIS-顺时针,CIRCLE_COUNTERCLOCKWISE-逆时针
* @note: 
* @retval 0:执行成功
*/
uint8_t circle_inc_move(uint32_t radius_step, circle_dir_typedef dir, quadrant_typedef quadrant)
{
	if (0 == radius_step)
	{
		return 1;
	}
	
	g_circle.f_e = 0;							              // 偏差方程置零
	
	if (CIRCLE_CLOCKWISE == dir)
	{
		if (quadrant == FIRST_QUADRANT)
		{
			/* 起点相对于圆心的坐标,圆心视为坐标轴的原点 */
			g_rel_position_x = 0;    	// 当前位置就是起点
			g_rel_position_y = radius_step;    						// 将圆心坐标视为坐标轴的原点,得到当前位置相对于圆心的坐标
			
			 /* 终点坐标 */
			g_circle.end_x = radius_step; // 相对于圆心的终点坐标
			g_circle.end_y = 0; // 相对于圆心的终点坐标
			
			motor_x_dir = MOTOR_FORWARD;
			MOTOR_X_DIR_FORWARD;
			motor_y_dir = MOTOR_REVERSE;
			MOTOR_Y_DIR_REVERSE;
			
			g_circle.active_axis = MOTOR_X;
			g_circle.f_e = g_circle.f_e + g_rel_position_x * 2 + 1;// 偏差方程的计算
		}
		else if (quadrant == SECOND_QUADRANT)
		{
			/* 起点相对于圆心的坐标,圆心视为坐标轴的原点 */
			g_rel_position_x = -radius_step;    	// 当前位置就是起点
			g_rel_position_y = 0;    						// 将圆心坐标视为坐标轴的原点,得到当前位置相对于圆心的坐标
			
			 /* 终点坐标 */
			g_circle.end_x = 0; // 相对于圆心的终点坐标
			g_circle.end_y = radius_step; // 相对于圆心的终点坐标
			
			motor_x_dir = MOTOR_FORWARD;
			MOTOR_X_DIR_FORWARD;
			motor_y_dir = MOTOR_FORWARD;
			MOTOR_Y_DIR_FORWARD;
			
			g_circle.active_axis = MOTOR_Y;
			g_circle.f_e = g_circle.f_e + g_rel_position_y * 2 + 1;// 偏差方程的计算
		}
		else if (quadrant == THIRD_QUADRANT)
		{
			/* 起点相对于圆心的坐标,圆心视为坐标轴的原点 */
			g_rel_position_x = 0;    	// 当前位置就是起点
			g_rel_position_y = -radius_step;    						// 将圆心坐标视为坐标轴的原点,得到当前位置相对于圆心的坐标
			
			 /* 终点坐标 */
			g_circle.end_x = -radius_step; // 相对于圆心的终点坐标
			g_circle.end_y = 0; // 相对于圆心的终点坐标
			
			motor_x_dir = MOTOR_REVERSE;
			MOTOR_X_DIR_REVERSE;
			motor_y_dir = MOTOR_FORWARD;
			MOTOR_Y_DIR_FORWARD;
			
			g_circle.active_axis = MOTOR_X;
			g_circle.f_e = g_circle.f_e - g_rel_position_x * 2 + 1;// 偏差方程的计算
		}
		else if (quadrant == FOURTH_QUADRANT)
		{
			/* 起点相对于圆心的坐标,圆心视为坐标轴的原点 */
			g_rel_position_x = radius_step;    	// 当前位置就是起点
			g_rel_position_y = 0;    						// 将圆心坐标视为坐标轴的原点,得到当前位置相对于圆心的坐标
			
			 /* 终点坐标 */
			g_circle.end_x = 0; // 相对于圆心的终点坐标
			g_circle.end_y = -radius_step; // 相对于圆心的终点坐标
			
			motor_x_dir = MOTOR_REVERSE;
			MOTOR_X_DIR_REVERSE;
			motor_y_dir = MOTOR_REVERSE;
			MOTOR_Y_DIR_REVERSE;
			
			g_circle.active_axis = MOTOR_Y;
			g_circle.f_e = g_circle.f_e - g_rel_position_y * 2 + 1;// 偏差方程的计算
		}
		else
		{
			return 1;
		}
	}
	else if (CIRCLE_COUNTERCLOCKWISE == dir)
	{
		if (quadrant == FIRST_QUADRANT)
		{
			/* 起点相对于圆心的坐标,圆心视为坐标轴的原点 */
			g_rel_position_x = radius_step;    	// 当前位置就是起点
			g_rel_position_y = 0;    						// 将圆心坐标视为坐标轴的原点,得到当前位置相对于圆心的坐标
			
			 /* 终点坐标 */
			g_circle.end_x = 0; // 相对于圆心的终点坐标
			g_circle.end_y = radius_step; // 相对于圆心的终点坐标
			
			motor_x_dir = MOTOR_REVERSE;
			MOTOR_X_DIR_REVERSE;
			motor_y_dir = MOTOR_FORWARD;
			MOTOR_Y_DIR_FORWARD;
			
			g_circle.active_axis = MOTOR_Y;
			g_circle.f_e = g_circle.f_e + g_rel_position_y * 2 + 1;// 偏差方程的计算
		}
		else if (quadrant == SECOND_QUADRANT)
		{
			/* 起点相对于圆心的坐标,圆心视为坐标轴的原点 */
			g_rel_position_x = 0;    	// 当前位置就是起点
			g_rel_position_y = radius_step;    						// 将圆心坐标视为坐标轴的原点,得到当前位置相对于圆心的坐标
			
			 /* 终点坐标 */
			g_circle.end_x = -radius_step; // 相对于圆心的终点坐标
			g_circle.end_y = 0; // 相对于圆心的终点坐标
			
			motor_x_dir = MOTOR_REVERSE;
			MOTOR_X_DIR_REVERSE;
			motor_y_dir = MOTOR_REVERSE;
			MOTOR_Y_DIR_REVERSE;
			
			g_circle.active_axis = MOTOR_X;
			g_circle.f_e = g_circle.f_e - g_rel_position_x * 2 + 1;// 偏差方程的计算
		}
		else if (quadrant == THIRD_QUADRANT)
		{
			/* 起点相对于圆心的坐标,圆心视为坐标轴的原点 */
			g_rel_position_x = -radius_step;    	// 当前位置就是起点
			g_rel_position_y = 0;    						// 将圆心坐标视为坐标轴的原点,得到当前位置相对于圆心的坐标
			
			 /* 终点坐标 */
			g_circle.end_x = 0; // 相对于圆心的终点坐标
			g_circle.end_y = -radius_step; // 相对于圆心的终点坐标
			
			motor_x_dir = MOTOR_FORWARD;
			MOTOR_X_DIR_FORWARD;
			motor_y_dir = MOTOR_REVERSE;
			MOTOR_Y_DIR_REVERSE;
			
			g_circle.active_axis = MOTOR_Y;
			g_circle.f_e = g_circle.f_e - g_rel_position_y * 2 + 1;// 偏差方程的计算
		}
		else if (quadrant == FOURTH_QUADRANT)
		{
			/* 起点相对于圆心的坐标,圆心视为坐标轴的原点 */
			g_rel_position_x = 0;    	// 当前位置就是起点
			g_rel_position_y = -radius_step;    						// 将圆心坐标视为坐标轴的原点,得到当前位置相对于圆心的坐标
			
			 /* 终点坐标 */
			g_circle.end_x = radius_step; // 相对于圆心的终点坐标
			g_circle.end_y = 0; // 相对于圆心的终点坐标
			
			motor_x_dir = MOTOR_FORWARD;
			MOTOR_X_DIR_FORWARD;
			motor_y_dir = MOTOR_FORWARD;
			MOTOR_Y_DIR_FORWARD;
			
			g_circle.active_axis = MOTOR_X;
			g_circle.f_e = g_circle.f_e + g_rel_position_x * 2 + 1;// 偏差方程的计算
		}
		else
		{
			return 1;
		}
	}
	else
	{
		return 1;
	}

  /* 不符合圆的坐标方程 */
  if ((pow(g_rel_position_x, 2) + pow(g_rel_position_y, 2)) != (pow(g_circle.end_x, 2) + pow(g_circle.end_y, 2)))
	{
		return 1;
	}
	
  /* 计算总的步数 */
  g_circle.end_y = radius_step;
  g_circle.end_x = radius_step;
  g_circle.end_pulse = g_circle.end_y + g_circle.end_x;  // 从起点到终点的脉冲数

	__HAL_TIM_CLEAR_IT(&htim8, TIM_IT_UPDATE); 
	
	if (MOTOR_X == g_circle.active_axis)
	{
		TIM8->CCR1 = g_step_timer_pulse_num >> 1;
		TIM8->ARR = g_step_timer_pulse_num;
		HAL_TIM_PWM_Start_IT(&htim8, TIM_CHANNEL_1);
	}
	else if (MOTOR_Y == g_circle.active_axis)
	{
		TIM8->CCR2 = g_step_timer_pulse_num >> 1;
		TIM8->ARR = g_step_timer_pulse_num;
		HAL_TIM_PWM_Start_IT(&htim8, TIM_CHANNEL_2);
	}
	else 
	{
		return 1;
	}
	
	return 0;
}


/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file    stm32f4xx_it.c
  * @brief   Interrupt Service Routines.
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2022 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32f4xx_it.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

#include "bsp_motor.h"

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */

/* USER CODE END TD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/* External variables --------------------------------------------------------*/
extern TIM_HandleTypeDef htim8;
extern UART_HandleTypeDef huart1;
/* USER CODE BEGIN EV */

/* USER CODE END EV */

/******************************************************************************/
/*           Cortex-M4 Processor Interruption and Exception Handlers          */
/******************************************************************************/
/**
  * @brief This function handles Non maskable interrupt.
  */
void NMI_Handler(void)
{
  /* USER CODE BEGIN NonMaskableInt_IRQn 0 */

  /* USER CODE END NonMaskableInt_IRQn 0 */
  /* USER CODE BEGIN NonMaskableInt_IRQn 1 */
  while (1)
  {
  }
  /* USER CODE END NonMaskableInt_IRQn 1 */
}

/**
  * @brief This function handles Hard fault interrupt.
  */
void HardFault_Handler(void)
{
  /* USER CODE BEGIN HardFault_IRQn 0 */

  /* USER CODE END HardFault_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_HardFault_IRQn 0 */
    /* USER CODE END W1_HardFault_IRQn 0 */
  }
}

/**
  * @brief This function handles Memory management fault.
  */
void MemManage_Handler(void)
{
  /* USER CODE BEGIN MemoryManagement_IRQn 0 */

  /* USER CODE END MemoryManagement_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */
    /* USER CODE END W1_MemoryManagement_IRQn 0 */
  }
}

/**
  * @brief This function handles Pre-fetch fault, memory access fault.
  */
void BusFault_Handler(void)
{
  /* USER CODE BEGIN BusFault_IRQn 0 */

  /* USER CODE END BusFault_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_BusFault_IRQn 0 */
    /* USER CODE END W1_BusFault_IRQn 0 */
  }
}

/**
  * @brief This function handles Undefined instruction or illegal state.
  */
void UsageFault_Handler(void)
{
  /* USER CODE BEGIN UsageFault_IRQn 0 */

  /* USER CODE END UsageFault_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_UsageFault_IRQn 0 */
    /* USER CODE END W1_UsageFault_IRQn 0 */
  }
}

/**
  * @brief This function handles System service call via SWI instruction.
  */
void SVC_Handler(void)
{
  /* USER CODE BEGIN SVCall_IRQn 0 */

  /* USER CODE END SVCall_IRQn 0 */
  /* USER CODE BEGIN SVCall_IRQn 1 */

  /* USER CODE END SVCall_IRQn 1 */
}

/**
  * @brief This function handles Debug monitor.
  */
void DebugMon_Handler(void)
{
  /* USER CODE BEGIN DebugMonitor_IRQn 0 */

  /* USER CODE END DebugMonitor_IRQn 0 */
  /* USER CODE BEGIN DebugMonitor_IRQn 1 */

  /* USER CODE END DebugMonitor_IRQn 1 */
}

/**
  * @brief This function handles Pendable request for system service.
  */
void PendSV_Handler(void)
{
  /* USER CODE BEGIN PendSV_IRQn 0 */

  /* USER CODE END PendSV_IRQn 0 */
  /* USER CODE BEGIN PendSV_IRQn 1 */

  /* USER CODE END PendSV_IRQn 1 */
}

/**
  * @brief This function handles System tick timer.
  */
void SysTick_Handler(void)
{
  /* USER CODE BEGIN SysTick_IRQn 0 */

  /* USER CODE END SysTick_IRQn 0 */
  HAL_IncTick();
  /* USER CODE BEGIN SysTick_IRQn 1 */

  /* USER CODE END SysTick_IRQn 1 */
}

/******************************************************************************/
/* STM32F4xx Peripheral Interrupt Handlers                                    */
/* Add here the Interrupt Handlers for the used peripherals.                  */
/* For the available peripheral interrupt handler names,                      */
/* please refer to the startup file (startup_stm32f4xx.s).                    */
/******************************************************************************/

/**
  * @brief This function handles USART1 global interrupt.
  */
void USART1_IRQHandler(void)
{
  /* USER CODE BEGIN USART1_IRQn 0 */

  /* USER CODE END USART1_IRQn 0 */
  HAL_UART_IRQHandler(&huart1);
  /* USER CODE BEGIN USART1_IRQn 1 */

  /* USER CODE END USART1_IRQn 1 */
}

/**
  * @brief This function handles TIM8 update interrupt and TIM13 global interrupt.
  */
void TIM8_UP_TIM13_IRQHandler(void)
{
  /* USER CODE BEGIN TIM8_UP_TIM13_IRQn 0 */

  /* USER CODE END TIM8_UP_TIM13_IRQn 0 */
  HAL_TIM_IRQHandler(&htim8);
  /* USER CODE BEGIN TIM8_UP_TIM13_IRQn 1 */

  /* USER CODE END TIM8_UP_TIM13_IRQn 1 */
}

/* USER CODE BEGIN 1 */

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	if (MOTOR_X == g_circle.active_axis)
	{
		HAL_TIM_PWM_Stop_IT(&htim8, TIM_CHANNEL_1);
		g_steps_done_x++;
		
		if (MOTOR_FORWARD == motor_x_dir)
		{
			g_rel_position_x++;
		}
		else
		{
			g_rel_position_x--;
		}
	}
	else if (MOTOR_Y == g_circle.active_axis)
	{
		HAL_TIM_PWM_Stop_IT(&htim8, TIM_CHANNEL_2);
		g_steps_done_y++;
		
		if (MOTOR_FORWARD == motor_y_dir)
		{
			g_rel_position_y++;
		}
		else
		{
			g_rel_position_y--;
		}
	}
	else	/* ERROR */
	{
		g_motor_state = MOTOR_STOP;
		return;
	}
	
	if (g_steps_done_x + g_steps_done_y >= g_steps_total)	/* 运行完成 */
	{
		g_motor_state = MOTOR_STOP;
		return;
	}

	/* 终点判别:总步长 */
  g_circle.end_pulse--;
  if (0 == g_circle.end_pulse)
  {
		if (CIRCLE_COUNTERCLOCKWISE == g_circle.inter_dir)
		{
			if (g_circle.qua_points == FIRST_QUADRANT)
			{
				g_circle.qua_points = SECOND_QUADRANT;
			}
			else if (g_circle.qua_points == SECOND_QUADRANT)
			{
				g_circle.qua_points = THIRD_QUADRANT;
			}
			else if (g_circle.qua_points == THIRD_QUADRANT)
			{
				g_circle.qua_points = FOURTH_QUADRANT;
			}
			else if (g_circle.qua_points == FOURTH_QUADRANT)
			{
				g_motor_state = MOTOR_STOP;
				return;
			}
			else
			{
				g_motor_state = MOTOR_STOP;
				return;
			}
		}
		else
		{
			if (g_circle.qua_points == FIRST_QUADRANT)
			{
				g_motor_state = MOTOR_STOP;
				return;
			}
			else if (g_circle.qua_points == SECOND_QUADRANT)
			{
				g_circle.qua_points = FIRST_QUADRANT;
			}
			else if (g_circle.qua_points == THIRD_QUADRANT)
			{
				g_circle.qua_points = SECOND_QUADRANT;
			}
			else if (g_circle.qua_points == FOURTH_QUADRANT)
			{
				g_circle.qua_points = THIRD_QUADRANT;
			}
			else
			{
				g_motor_state = MOTOR_STOP;
				return;
			}
		}
		
		circle_inc_move(g_steps_radius, g_circle.inter_dir, g_circle.qua_points);
  }
  else
  {
		/* 根据上一次的偏差判断下一步进给方向,同时计算下一次的偏差 */
		if (g_circle.inter_dir == CIRCLE_COUNTERCLOCKWISE)       // 插补方向:逆时针圆弧
		{
			if (g_circle.f_e < 0)              // 偏差方程 < 0 ,说明当前位置位于圆弧内侧,应向圆外进给
			{	
				if ((g_circle.qua_points == SECOND_QUADRANT) || (g_circle.qua_points == FOURTH_QUADRANT))// 第二和第四象限,当偏差<0时都是向X轴进给
				{
					g_circle.active_axis = MOTOR_X;
				}
				else    // 在第一和第三象限,偏差<0,都是向Y轴进给
				{
					g_circle.active_axis = MOTOR_Y;
				}
			}
			else if (g_circle.f_e >= 0)         // 偏差方程 >= 0 ,说明当前位置位于圆弧外侧,应向圆内进给
			{
				if ((g_circle.qua_points == SECOND_QUADRANT) || (g_circle.qua_points == FOURTH_QUADRANT))
				{  
					g_circle.active_axis = MOTOR_Y;
				}
				else 
				{
					g_circle.active_axis = MOTOR_X;
				}
			}
		}
		else
		{
			if (g_circle.f_e < 0)              // 偏差方程 < 0 ,说明当前位置位于圆弧内侧,应向圆外进给
			{	
				if ((g_circle.qua_points == FIRST_QUADRANT) || (g_circle.qua_points == THIRD_QUADRANT))// 第一和第三象限,当偏差<0时都是向X轴进给
				{
					g_circle.active_axis = MOTOR_X;
				}
				else    // 在第二和第四象限,偏差<0,都是向Y轴进给
				{
					g_circle.active_axis = MOTOR_Y;
				}
			}
			else if (g_circle.f_e >= 0)         // 偏差方程 >= 0 ,说明当前位置位于圆弧外侧,应向圆内进给
			{
				if ((g_circle.qua_points == FIRST_QUADRANT) || (g_circle.qua_points == THIRD_QUADRANT))
				{  
					g_circle.active_axis = MOTOR_Y;
				}
				else 
				{
					g_circle.active_axis = MOTOR_X;
				}
			}
		}
		
		if (CIRCLE_COUNTERCLOCKWISE == g_circle.inter_dir)
		{
			if (MOTOR_X == g_circle.active_axis)
			{
				if ((g_circle.qua_points == FIRST_QUADRANT) || (g_circle.qua_points == SECOND_QUADRANT))
				{
					g_circle.f_e = g_circle.f_e - 2 * g_rel_position_x + 1;// 偏差方程的计算
				}
				else
				{
					g_circle.f_e = g_circle.f_e + 2 * g_rel_position_x + 1;// 偏差方程的计算
				}
			}
			else
			{
				if ((g_circle.qua_points == FIRST_QUADRANT) || (g_circle.qua_points == FOURTH_QUADRANT))
				{
					g_circle.f_e = g_circle.f_e + 2 * g_rel_position_y + 1;// 偏差方程的计算
				}
				else
				{
					g_circle.f_e = g_circle.f_e - 2 * g_rel_position_y + 1;// 偏差方程的计算
				}
			}
		}
		else
		{
			if (MOTOR_X == g_circle.active_axis)
			{
				if ((g_circle.qua_points == FIRST_QUADRANT) || (g_circle.qua_points == SECOND_QUADRANT))
				{
					g_circle.f_e = g_circle.f_e + 2 * g_rel_position_x + 1;// 偏差方程的计算
				}
				else
				{
					g_circle.f_e = g_circle.f_e - 2 * g_rel_position_x + 1;// 偏差方程的计算
				}
			}
			else
			{
				if ((g_circle.qua_points == FIRST_QUADRANT) || (g_circle.qua_points == FOURTH_QUADRANT))
				{
					g_circle.f_e = g_circle.f_e - 2 * g_rel_position_y + 1;// 偏差方程的计算
				}
				else
				{
					g_circle.f_e = g_circle.f_e + 2 * g_rel_position_y + 1;// 偏差方程的计算
				}
			}
		}
		
		if (MOTOR_X == g_circle.active_axis)
		{
			TIM8->CCR1 = g_step_timer_pulse_num >> 1;
			TIM8->ARR = g_step_timer_pulse_num;
			HAL_TIM_PWM_Start_IT(&htim8, TIM_CHANNEL_1);
		}
		else if (MOTOR_Y == g_circle.active_axis)
		{
			TIM8->CCR2 = g_step_timer_pulse_num >> 1;
			TIM8->ARR = g_step_timer_pulse_num;
			HAL_TIM_PWM_Start_IT(&htim8, TIM_CHANNEL_2);
		}
		else	/* ERROR */
		{
			g_motor_state = MOTOR_STOP;
			return;
		}
  }
}

/* USER CODE END 1 */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

总结:
1、
在这里插入图片描述
2、
在这里插入图片描述
3、
在这里插入图片描述
4、
在这里插入图片描述
5、
在这里插入图片描述
6、
在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的使用C语言实现STM32F407控制XY平台的步进电机插补算法的代码示例: ```c #include "stm32f407xx.h" #define X_STEP_PIN GPIO_PIN_0 #define Y_STEP_PIN GPIO_PIN_1 #define X_DIR_PIN GPIO_PIN_2 #define Y_DIR_PIN GPIO_PIN_3 #define X_MAX 1000 #define Y_MAX 1000 uint16_t x_pos = 0; uint16_t y_pos = 0; uint16_t x_target = 0; uint16_t y_target = 0; void delay(uint32_t ms) { for (uint32_t i = 0; i < ms * 1000; i++) { asm("nop"); } } void set_x_dir(uint8_t dir) { if (dir == 0) { HAL_GPIO_WritePin(GPIOA, X_DIR_PIN, GPIO_PIN_RESET); } else { HAL_GPIO_WritePin(GPIOA, X_DIR_PIN, GPIO_PIN_SET); } } void set_y_dir(uint8_t dir) { if (dir == 0) { HAL_GPIO_WritePin(GPIOA, Y_DIR_PIN, GPIO_PIN_RESET); } else { HAL_GPIO_WritePin(GPIOA, Y_DIR_PIN, GPIO_PIN_SET); } } void step_x(uint8_t dir) { set_x_dir(dir); HAL_GPIO_WritePin(GPIOA, X_STEP_PIN, GPIO_PIN_SET); delay(1); HAL_GPIO_WritePin(GPIOA, X_STEP_PIN, GPIO_PIN_RESET); delay(1); } void step_y(uint8_t dir) { set_y_dir(dir); HAL_GPIO_WritePin(GPIOA, Y_STEP_PIN, GPIO_PIN_SET); delay(1); HAL_GPIO_WritePin(GPIOA, Y_STEP_PIN, GPIO_PIN_RESET); delay(1); } void move_x(uint16_t steps, uint8_t dir) { for (uint16_t i = 0; i < steps; i++) { step_x(dir); if (dir == 0) { x_pos--; } else { x_pos++; } } } void move_y(uint16_t steps, uint8_t dir) { for (uint16_t i = 0; i < steps; i++) { step_y(dir); if (dir == 0) { y_pos--; } else { y_pos++; } } } void move_to(uint16_t x, uint16_t y) { int16_t x_diff = x - x_pos; int16_t y_diff = y - y_pos; uint8_t x_dir = x_diff >= 0 ? 1 : 0; uint8_t y_dir = y_diff >= 0 ? 1 : 0; x_diff = x_diff >= 0 ? x_diff : -x_diff; y_diff = y_diff >= 0 ? y_diff : -y_diff; if (x_diff > y_diff) { float y_step = (float)y_diff / (float)x_diff; for (uint16_t i = 0; i < x_diff; i++) { move_x(1, x_dir); y_target += y_step; if (y_target >= 1) { uint16_t y_steps = (uint16_t)y_target; move_y(y_steps, y_dir); y_target -= y_steps; } } } else { float x_step = (float)x_diff / (float)y_diff; for (uint16_t i = 0; i < y_diff; i++) { move_y(1, y_dir); x_target += x_step; if (x_target >= 1) { uint16_t x_steps = (uint16_t)x_target; move_x(x_steps, x_dir); x_target -= x_steps; } } } } int main(void) { HAL_Init(); __HAL_RCC_GPIOA_CLK_ENABLE(); GPIO_InitTypeDef GPIO_InitStruct = {0}; GPIO_InitStruct.Pin = X_STEP_PIN | Y_STEP_PIN | X_DIR_PIN | Y_DIR_PIN; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); while (1) { move_to(X_MAX, Y_MAX); delay(1000); move_to(0, 0); delay(1000); } } ``` 这个示例代码使用了GPIO控制电机的步进和方向信号,并且实现了一个简单的插补算法来控制XY平台移动到目标位置。请注意,这只是一个简单的示例代码,实际情况下可能需要进行更多的优化和错误处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值