cancel
Showing results for 
Search instead for 
Did you mean: 

Timer issue

kalhana
Associate II
Posted on February 08, 2016 at 17:03

Hi,

I'm having an issue setting up TIM1 for PWM on the STM32F446.

In the following code, the PWM works for TIM2 but not for TIM1.

Any ideas?

Thank you.

  RCC->APB1ENR |= (1UL << 0); // TIM2 clock enable

  TIM2->PSC   = 89;               // set prescaler   = 1 MHz

  TIM2->ARR   = 999;              // set auto-reload =  for 1 kHz

  TIM2->CCR2 = 15;                // 1.5% duty cycle

  TIM2->CCMR1 |= 0x6800;

  TIM2->CR1 |= 0x80;  

  TIM2->CCER |= 0x10;

  TIM2->EGR |= 0x01;

  TIM2->CR1 |= 0x01;

  

  RCC->AHB1ENR |= (1UL << 0);       // GPIOA clock enable

  GPIOA->MODER |= (2UL << 2*1);     // PA1  - is alt function

  GPIOA->OSPEEDR |= (3UL << 2*1);   // PA1  - is high speed

  GPIOA->AFR[0] |= (1 << 4);        // PA1 - AF1 mapping

  

//================================================================

  RCC->APB2ENR |= (1UL << 0); // TIM1 clock enable

  TIM1->PSC   = 179;           // set prescaler   = 1 MHz

  TIM1->ARR   = 999;          // set auto-reload =  for 1 kHz

  TIM1->CCR2 = 15;            // 1.5% duty cycle

  TIM1->CCMR1 |= 0x6800;

  TIM1->CR1 |= 0x80;  

  TIM1->CCER |= 0x10;

  TIM1->EGR |= 0x01;

  TIM1->CR1 |= 0x01;

  

  RCC->AHB1ENR |= (1UL << 0);       // GPIOA clock enable

  GPIOA->MODER |= (2UL << 2*9);     // PA9  - is alt function

  GPIOA->OSPEEDR |= (3UL << 2*9);   // PA9  - is high speed

  GPIOA->AFR[1] |= (1 << 4);        // PA9 - AF1 mapping
4 REPLIES 4
Posted on February 08, 2016 at 17:11

Ah, the classical TIM1/TIM8 gotcha #1.

Set TIMx_BDTR.MOE.

JW
Radosław
Senior
Posted on February 08, 2016 at 17:32

Do you love magic numbers? Why?

This code is not readable.

kalhana
Associate II
Posted on February 08, 2016 at 17:44

Thank you, that was the issue, now working.

Well I started using STM32 back in 2009 when there was no HAL/CMIS stuff as far as I know. And I prefer setting values directly to registers (Although I do usually set #defines and is a bit better than this code I posted which was done in a hurry to see if it works).

I really don't like HAL code where it has to run though so many lines of code (and jump through functions) just to set the value for 1 register (it is actually very hard to follow never mind the penalty in CPU time). Also, I never use STM's Init functions that you need to pass Init structures to, I like more control over what I'm doing.

Radosław
Senior
Posted on February 08, 2016 at 17:52

Use CMSIS vendor file for bits definition.