0
\$\begingroup\$

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:

https://www.st.com/resource/en/reference_manual/dm00119316-stm32f411xc-e-advanced-arm-based-32-bit-mcus-stmicroelectronics.pdf

code:

//PA5:TIM2_CH1
// 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 OUTPUT COMPARE CONFIG
RCC->APB1ENR |=1;
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;
while(1)
{}
}

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

SamGibson
18.5k5 gold badges42 silver badges65 bronze badges
asked Dec 16, 2020 at 11:42
\$\endgroup\$
1
  • 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\$ Commented Dec 16, 2020 at 14:44

1 Answer 1

1
\$\begingroup\$

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);
 (void)tmpreg;
}
// __IO expands to the volatile keyword
answered Dec 16, 2020 at 20:56
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.