cancel
Showing results for 
Search instead for 
Did you mean: 

Problem with Timer2

SSmit.13
Senior

Hi

  I have am using the Timer2 on the STM32L433 chip, and for some reason the interupt gets called as soon as timer is started.  Below is my code, and the  clocks are running at 60MHz.  Anyone any idea what I have done wrong?

 

Many Thanks

Scott.

 

void main(void)
{
  .....
  Timer2_Init();
  Start_OneShotTimer2(3000);  //set for 3 seconds, but interupt routine gets called straight away

 while(1){}
}

void Timer2_Init(void)
{
	 // Enable Timer 2 clock
	RCC->APB1ENR1 |= RCC_APB1ENR1_TIM2EN;

	// Configure the timer for one-pulse mode
	TIM2->CR1 |= TIM_CR1_OPM; // One-Pulse Mode (counter stops after update event)

	// Enable TIM2 interrupt in NVIC
	NVIC_EnableIRQ(TIM2_IRQn);
}


void Start_OneShotTimer2(uint32_t milliseconds)
{
	uint32_t prescaler;
	// 1. Stop the timer before modifying its configuration
	TIM2->CR1 &= ~TIM_CR1_CEN;   // Stop the timer (disable counter)

	// 2. Clear any previous interrupt flags
	TIM2->SR = 0;                 // Clear all status flags, including UIF

	// 3. Disable the interrupt while configuring the timer
	TIM2->DIER &= ~TIM_DIER_UIE;  // Disable the update interrupt

	// 4. Calculate the prescaler (prescale to 1 µs)
	TIM2->PSC = 59999;       // Set the prescaler for 1 µs ticks

	// 5. Set the auto-reload value for the desired delay (milliseconds converted to µs)
	uint32_t arr = (milliseconds * 1000) - 1; // Convert ms to µs
	TIM2->ARR = arr;                 // Set auto-reload value

	// 6. Reset the counter to ensure it starts from 0
	TIM2->CNT = 0;                   // Reset the counter value

	// 7. Enable the update interrupt (only now)
	TIM2->DIER |= TIM_DIER_UIE;      // Enable the update interrupt

	// 8. Start the timer
	TIM2->CR1 |= TIM_CR1_CEN;
}

void TIM2_IRQHandler(void)
{
    if (TIM2->SR & TIM_SR_UIF)
    { // Check for the update interrupt flag
        TIM2->SR &= ~TIM_SR_UIF; // Clear the interrupt flag
.......

    }
   
}

 

 

0 REPLIES 0