I am using an stm32f411re nucleo board. I am trying to configure the Tim2_ch1 module in output compare mode.

I have written the code by referring to the reference manual:




// clock frequency:16Mhz


#include "stm32f4xx.h"         // Device header

// toggle led at 1hz using TIM2 output COMPARE MODE

int main(void)


 RCC->AHB1ENR |=1;

GPIOA->MODER |=0X800; //PA_5 is configured in alternate function mode

GPIOA->AFR[0] |=0X00100000; // Tim2_ch1 is assigned to PA_5



TIM2->PSC |=1600-1;   

TIM2->ARR |=10000-1;   //clock frequency is divided by prescalar and auto reload

TIM2->CCMR1 |=0X30;    

TIM2->CCR1 |=0;

TIM2->CCER |=1;

TIM2->CNT |=0;

TIM2->CR1 |=1;




This code is not working. Is there any issue with the code?

  • 1
    \$\begingroup\$ Do you really mean to use the |= (OR-equals) operator for every register assignment? That seems wrong for TIM2->PSC, TIM2->ARR, and probably others but I stopped checking. \$\endgroup\$
    – kkrambo
    Dec 16, 2020 at 14:44

1 Answer 1


There doesn't look like to be anything wrong with the assignments of the regsiters.
I believe the right bits are being set. Magic numbers don't help.
Please use the defines in the header file. eg: RCC_AHB1ENR_GPIOAEN

Although TIM2->CNT |=0; doesn't make sense.

I suspect the problem is with the RCC->APB1ENR |=1; and the other RCC write. You need at least one APB clock delay to ensure it is actually set before doing anything else. Simple way to do that is to read it back.

Snippet from STM32 LL library:

__STATIC_INLINE void LL_AHB1_GRP1_EnableClock(uint32_t Periphs)
  __IO uint32_t tmpreg;
  SET_BIT(RCC->AHB1ENR, Periphs);
  /* Delay after an RCC peripheral clock enabling */
  tmpreg = READ_BIT(RCC->AHB1ENR, Periphs);
// __IO expands to the volatile keyword
  • \$\begingroup\$ thanks for your help @jeroen3 \$\endgroup\$ Dec 17, 2020 at 13:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.