cancel
Showing results for 
Search instead for 
Did you mean: 

STM32 Timer set in output compare / one pulse mode

FFuma
Associate II

Hi everyone,

I'm trying to set a timer so that it works in output compare and also in one pulse mode, as I want it to only fire once. Below is my code for initiating timer1 in output compare/one pulse. Is this setup correct? One issue I'm having is that when the periodElapsedCallback is fired I set a flag which causes a variable count to be printed in the main loop in the main loop. Count is initialised to 0 and on my console I see it increment up to 1...so the values 0 & 1 are printed meaning that the timer ran twice. Any ideas what could be going wrong?

EDIT:if i comment out htim1.Instance->CR1 |= TIM_OPMODE_SINGLE; count keeps increasing (as it should since the timer resets) I just cant understand why when OPMODE is enabled it runs twice instead of once!

EDIT2: I've come to the conclusion that there are other factors which can trigger an UEV interrupt to be triggered but I can't find a list or something.

void MX_TIM1_Init(void){
 
	  htim1.Instance = TIM1;
	  htim1.Init.Prescaler = 12;
	  htim1.Init.CounterMode = TIM_COUNTERMODE_UP;
	  htim1.Init.Period = 65535;
	  htim1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
	  htim1.Init.RepetitionCounter = 0;
	  HAL_TIM_OC_Init(&htim1);
	  
	  htim1.Instance->CR1 &= ~TIM_CR1_OPM; 
	  htim1.Instance->CR1 |= TIM_OPMODE_SINGLE;//enable single shot mode
 
 
	  sConfig.OCMode = TIM_OCMODE_TOGGLE;
	  sConfig.Pulse = 420;
	  sConfig.OCPolarity = TIM_OCPOLARITY_HIGH;
	  HAL_TIM_OC_ConfigChannel(&htim1, &sConfig, TIM_CHANNEL_2);
}
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
  if(htim->Instance == TIM1){
	  HAL_GPIO_TogglePin(LD2_GPIO_Port, LD2_Pin);
	 onePulse=1;
 
}
}
int main(void)
 
{
 
	uint16_t diffCapture = 0;
	char msg[50]; 
	float frequency =0; 
	HAL_Init();
	SystemClock_Config();
	MX_GPIO_Init();
	MX_UART_Init();
	MX_TIM3_Init();
	MX_TIM1_Init();
 
	HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);
	HAL_TIM_OC_Start(&htim1,TIM_CHANNEL_2);
 
       HAL_TIM_IC_Start_IT(&htim3,TIM_CHANNEL_1);
 	while(1){
 		while (onePulse != 1);
 		 char Count[10];
 		 sprintf(Count,"\r\n%d",count);
 		 HAL_UART_Transmit(&huart2, (uint8_t*)Count,strlen(Count), HAL_MAX_DELAY);
 		 count++;
 		 onePulse =0;
     }
}

1 REPLY 1

> EDIT2: I've come to the conclusion that there are other factors which can trigger an UEV interrupt to be triggered but I can't find a list or something.

Writing 1 to TIMx_EGR.UG for example. And I'd bet some of the Cube/HAL timer initialization function does that (in order to force the TIMx_PSC to be active immediately).

I don't Cube.

JW