cancel
Showing results for 
Search instead for 
Did you mean: 

Change Timer and PWM period "on the fly" ?

JTurp
Associate II

Hi, I'm currently trying to set up acceleration and deceleration phases for a stepper motor. For that I'm tryin to change the frequency of the PWM [timer1] ( and the Timer [TIMER1] interrup associated). I'm working on a STM32F407-DISC. I found out the macro __HAL_TIM_SET_AUTORELOAD but I don't see any changes on the period. Here is my interruption that update the period :

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
	{
		UNUSED(htim);
		
		if(htim->Instance == TIM1){
			
				// Count the number of times the ISR has been triggered
				ticksPassed++;
			
			if(ticks_to_make >= ticksPassed ){
				
				if(useAcceleration){
					
					// Accelerate
					if(numberOfTicksMade < ticksToAccelerate){
						current_period -= (uint16_t)accelerationPerTickInteger;
						__HAL_TIM_SET_AUTORELOAD(&htim1,current_period);
						
						// activate timer
						HAL_TIM_Base_Start_IT(&htim1);
							
						//activating the PWM
						HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_1);
						HAL_TIMEx_PWMN_Start(&htim1, TIM_CHANNEL_1);
 
						}
					
				else{
				
				// Decelerate
				if(ticksPassed > decelerationTick){
					
					current_period += (uint16_t)accelerationPerTickInteger;
					__HAL_TIM_SET_AUTORELOAD(&htim1,current_period);
					
					// activate timer
					HAL_TIM_Base_Start_IT(&htim1);
							
					//activating the PWM
					HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_1);
					HAL_TIMEx_PWMN_Start(&htim1, TIM_CHANNEL_1);
					}
				}
				}
		
		// When the steps have been made, stop the timer interrupt, unless the PERPETUAL_MOTION is activated
 
			}
			else{
				stepperStop(&htim1,TIM_CHANNEL_1);
			}
 
	}
		
}

2 REPLIES 2

Better just to write TIM1->ARR and TIM1->CCR1, if you don't have "preload" these will load cleanly at the next Update event from the shadow registers.

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..

Ok thanks and do I need to restart the PWM and the Timer after that ?