Nemanja
Nemanja

Reputation: 33

Configuring timer channel as output

I use NUCLEO-F042K6 board to generate a PWM signal. I use Timer2 for that purpose. Timer2 has 4 channels, but according to STM32F042x4 Datasheet CH1 cannot be redirected to physical pin. Picture 1: Timer 2 schematic - Reference manual [Picture 2: Alternate functions - Datasheet2 I still want to utilize Timer 2 and for that purpose I want to use CH2. Unfortunately, I am not able to get a PWM signal on the output. Here is my code:

void TIM2_setup(void){
// Enable Timer 2 clock
RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;
// I/O port A clock enable
RCC->AHBENR |= RCC_AHBENR_GPIOAEN;

//These bits are written by software to configure the I/O mode. 10: Alternate function mode
GPIOA->MODER |= (0x2UL << GPIO_MODER_MODER1_Pos);
//Alternate function AF1 selection for port A pin 1
GPIOA->AFR[0] |= (0x2UL << GPIO_AFRL_AFSEL1_Pos);

TIM2->CR1 |= TIM_CR1_CMS;
TIM2->CR1 |= TIM_CR1_ARPE;
// : PWM mode 1
TIM2->CCMR1 |= (0x6UL << TIM_CCMR1_OC2M_Pos);
TIM2->CCMR1 |= TIM_CCMR1_OC2PE;
TIM2->CCER |= TIM_CCER_CC2E;

TIM2->ARR = 8;
TIM2->CCR2 = 6;
TIM2->PSC = 0;
TIM2->CNT = 0;

TIM2->CR1 |= TIM_CR1_CEN;

}

I should mention that I configured Timer 3 with the (almost) same values, but using Channel 1 and it worked. I assume that the error lies in the registers configuration.

Upvotes: 0

Views: 453

Answers (1)

wek
wek

Reputation: 1213

Don't set TIM_CR1_ARPE before setting TIMx_ARR.

If you do so, the new ARR value gets active only upon next Update i.e. when TIMx_CNT reaches the default TIMx_ARR. Default TIMx_ARR is the maximum range which for TIM2 - a 32-bit timer - is 2^32-1, i.e. cca 500 seconds at the default 8MHz HSI clock. Would you wait those cca 8 minutes, you'd be rewarded by the output starting to toggle.

TIM3 is a 16-bit timer, so that "initial" delay is only a few ms which you did not notice.

So, set TIM_CR1_ARPE after you've set TIM2_ARR. Alternatively, you can force ARR update by setting TIMx_EGR.UG.

Other remarks:

  • most STM32 need a delay between clock enable in RCC and accessing given peripheral's registers
  • TIMx_PSC is unconditionally preloaded, so its new new value won't be active until update - you set it to 0 here, which is the default, so this does not matter at the moment
  • there's nothing wrong with using TIM2_CH1 on PA0, PA5, PA15. ST chose an unfortunate labelling of TIM2_CH1_ETR, but that just means, that if you don't use the ETR functionality, it's plain TIM2_CH1; and if you use the ETR functionality, don't use the CH1 functionality.

Upvotes: 1

Related Questions