Reputation: 33
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.
[
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
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:
Upvotes: 1