2021-04-03 07:35 PM
Hi 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;
}
}
}
Solved! Go to Solution.
2021-04-04 08:08 AM
It works very well with your program.
Thanks a lot.
2021-04-04 09:13 AM
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.
2021-04-04 04:13 PM
Yes, that’s what I will be doing as well. Thanks again for the help.