Search code examples
timerstm32

STM32F302R8. TIM2 as output and TIM15 as input does not work for me


I am learning to use the STM32F302R8 board and I have this problem.

TIM2 is configured with toggle output CH1 on PA0. (This works fine).

TIM15 is configured as input capture CH1 on PA2.

I have a jumper between PA0 and PA2.

The aim is that when TIM2 reaches the value of CCR1 it triggers the PA0 pin, which happens, and having the jumper with the PA2 pin should trigger the TIM15 input but this does not happen.

The while that checks the CC1IF flag never ends, it doesn't detect anything.

What can it be?

while (1)
{
  // wait until input edge is captured
  while ( !(TIM15->SR & TIM_SR_CC1IF)) {} 
  timestamp = TIM15->CCR1;      // read captured counter value
}

void mi_GPIO_Init ( void ) {
  RCC->AHBENR  |= RCC_AHBENR_GPIOAEN | RCC_AHBENR_GPIOBEN;
  GPIOA->MODER  &= ~GPIO_MODER_MODER0;   // clear PA0 mode
  GPIOA->MODER  |=  GPIO_MODER_MODER0_1; // set pin to alt function
  GPIOA->AFR[0] &= ~GPIO_AFRL_AFRL0;     // clear pin AF bits
  GPIOA->AFR[0] |=  0x0000001;           // set pin to AF1 for TIM2_CH1

  GPIOA->MODER  &= ~GPIO_MODER_MODER2;   // clear PA2 mode
  GPIOA->MODER  |=  GPIO_MODER_MODER2_1; // set pin to alt function
  GPIOA->AFR[0] &= ~GPIO_AFRL_AFRL2;     // clear pin AF bits
  GPIOA->AFR[0] |=  0x0000900;           // set pin to AF9 for TIM15_CH1

  // Configure TIM2 to wrap around at 1 Hz and toggle CH1 output when the counter value is 0
  RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;   // enable TIM2 clock
  TIM2->PSC = 800 - 1;          // divided by 800
  TIM2->ARR = 10000 -1;         // divided by 10000
  TIM2->CCMR1 = TIM_CCMR1_OC1M_0 | TIM_CCMR1_OC1M_1; // set output to toggle on match
                            // The rest of the bits are set to 0.
  TIM2->CCR1 = 0;               // set match value
  TIM2->CCER |= TIM_CCER_CC1E;  // enable CH1 compare mode
  TIM2->CNT = 0;                // clear timer counter
  TIM2->CR1 |= TIM_CR1_CEN;     // enable TIM2

  // Configure TIM15 to do input capture
  RCC->APB2ENR |= RCC_APB2ENR_TIM15EN;  // enable TIM15 clock
  TIM15->PSC = 8000 - 1;        // divided by 8000
  TIM15->ARR = 0xFFFF;          // count until ARR
  TIM15->CCMR1 &= ~TIM_CCMR1_CC1S; // set CH1 to capture at every edge
  TIM15->CCMR1 |= TIM_CCMR1_CC1S_0; // CC1 as input, IC1 is mapped on TI1
  TIM15->CCER |= TIM_CCER_CC1E; // enable CH1 capture rising edge
  TIM15->CR1 |= TIM_CR1_CEN;    // enable TIM15
}

Solution

  • I moved the clock trigger lines to the beginning of the code and instead of PA2 I use PB14 and now it works fine.