cancel
Showing results for 
Search instead for 
Did you mean: 

( STM32F411 ) TIM2 channel 1 can't toggle pin

TBorc.502
Associate

F(clock) = 16000000 Hz

Led is in TIM2 channel 1 , output compare mode , toggle on match

My code is :

void timer_set()

{

  // Enable TIM2 clock

  RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;

 // delay for RCC

 __asm("dsb");

  TIM2->CNT=0;

  TIM2->PSC = 15999;

  TIM2->ARR = 99;

  TIM2->CCR1 = 20;

  TIM2->CCMR1 = TIM_CCMR1_OC1M_0 | TIM_CCMR1_OC1M_1;

  TIM2->CCER = TIM_CCER_CC1E; // Enable compare output 1

  TIM2->CR1 = TIM_CR1_CEN;

}

but channel 1 / led can't toggle - what's wrong ??

4 REPLIES 4
TDK
Guru

Did you initialize the pin in AF mode?

If you feel a post has answered your question, please click "Accept as Solution".
TBorc.502
Associate

I can't initialize this ( AF ) any example ?

Maybe look at some examples in the STM32CubeF4 repository. Maybe use CubeMX/HAL until you understand and want to program at the register level. Up to you.
If you feel a post has answered your question, please click "Accept as Solution".
berendi
Principal

Refer to the GPIO chapter in the reference manual.

  • Enable GPIO clock in RCC->AHB1ENR for the pins to be used by the timer.
  • Set GPIO->MODER bits for the pin to alternate mode (0b10). Be careful when the pin is on GPIOA, setting/masking the wrong bits can disable the debugger interface.
  • Look up the AF number for TIM2_CH1 in the pin mapping table in the datasheet.
  • Put the AF number into the bitfield corresponding to the pin in the AFR[] registers. Note that AFRL corresponds to AFR[0], and AFRH to AFR[1].

E.g. to map TIM2_CH1 to PA0:

RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
RCC->AHB1ENR; // short delay might be necessary
GPIOA->MODER = (GPIOA->MODER & ~GPIOA_MODER_MODE0) | GPIOA_MODER_MODE0_1;
GPIOA->AFR[0] = (GPIOA->AFR[0] & ~GPIO_AFRL_AFSEL0) | (1u << GPIO_AFRL_AFSEL0_Pos);