cancel
Showing results for 
Search instead for 
Did you mean: 

Generating specified number of pulses using PWM

Ayemyitta
Associate II

0693W000008ye9AQAQ.png0693W000008ye95QAA.png0693W000008ye90QAA.png0693W000008ye8vQAA.png0693W000008ye8qQAA.png0693W000008ye8lQAA.png0693W000008ye8gQAA.pngHi All,

I am trying to generate required no of pulses using PWM. This is to implement to control stepper motor with position control.

I use HAL_TIM_PWM_Start_IT to start pulsing and count the no of pulses in HAL_TIM_PWM_PulseFinishedCallback.

I notice that the more the required pulses, the more the extra pulses will be generated. And also higher frequency will generate more extra pulses.

Attached is the initilization of the timer and call back function when the interrupt occur.

/**
  * @brief TIM3 Initialization Function
  * @param None
  * @retval None
  */
static void MX_TIM3_Init(void)
{
 
  /* USER CODE BEGIN TIM3_Init 0 */
 
  /* USER CODE END TIM3_Init 0 */
 
  TIM_MasterConfigTypeDef sMasterConfig = {0};
  TIM_OC_InitTypeDef sConfigOC = {0};
 
  /* USER CODE BEGIN TIM3_Init 1 */
 
  /* USER CODE END TIM3_Init 1 */
  htim3.Instance = TIM3;
  htim3.Init.Prescaler = 1-1;
  htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim3.Init.Period = 65535;
  htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_PWM_Init(&htim3) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigOC.OCMode = TIM_OCMODE_PWM1;
  sConfigOC.Pulse = 0;
  sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
  sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
  if (HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
  {
    Error_Handler();
  }
  __HAL_TIM_DISABLE_OCxPRELOAD(&htim3, TIM_CHANNEL_1);
  /* USER CODE BEGIN TIM3_Init 2 */
 
  /* USER CODE END TIM3_Init 2 */
  HAL_TIM_MspPostInit(&htim3);
 
}
static void StartStepControl(HSO_CH_Typedef channel)
{
	if (channel == CH2)
	{
		if(__i32TargetPosition[CH2] != *__i32CurrentPosition[CH2])
		{
			HAL_TIM_PWM_Start_IT(&htim3, TIM_CHANNEL_1);
			*__PulsingStatus[channel] = RUNNING;
		}
	}
 
}
void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim)
{
	if(htim == &htim3)
	{
		if (*__i32CurrentPosition[CH2] >= __i32TargetPosition[CH2])
		{
			HAL_TIM_PWM_Stop_IT(&htim3, TIM_CHANNEL_1);
			*__PulsingStatus[CH2] = PULSEDONE;
		}
		else
		{
			*__i32CurrentPosition[CH2] += 1;
		}
	}
}

12 REPLIES 12

It works very well with your program.

Thanks a lot.

DavidAlfa
Senior II

Nice! Is it a stepper motor? Then you will need to add ramp up / slow down somehow to not lose steps but also be able to reach faster speeds.

Yes, that’s what I will be doing as well. Thanks again for the help.