Skip to main content
Nick-
Associate II
March 8, 2022
Solved

STM32F303RE Tim2 ch2 PWM Mode

  • March 8, 2022
  • 2 replies
  • 2218 views

Hi everyone, I'm trying to use the Timer2 CH2 PWM Mode 1 to generate a 1 Hz signal with 50% Duty Cycle out of my PA0 pin but i can't get anything. Here's my code:

#include"stm32f3xx.h"
 
void TIM_PWM(void);
 
int main(void){
	TIM_PWM();
while(1){
}
}
 
void TIM_PWM(void){
	RCC->AHBENR |= (1U<<17); //AHBENR GPIOA
	RCC->APB1ENR |= (1U<<0); //APB1ENR TIM2
	GPIOA->MODER |= (1U<<1); //PA0 alternate function
	GPIOA->AFR[0] |= (1U<<0); //alternate function AF1 on PA0
	TIM2->PSC = 8000;
	TIM2->ARR = 1000;
	TIM2->CNT = 0;
	TIM2->CCR2 = 500; //capture compare CH2
	TIM2->CCMR1 |= (0b110<<12); //capture compare PWM mode 1
	TIM2->CCER |= (1U<<4); //capture compare CH2 output enable
	TIM2->CR1 = (1U<<0); //counter enable
}

I'm using a NUCLEO BOARD STM32F303RE. Clock is set to 8 Mhz.

Can someone help me? thanks in advance

This topic has been closed for replies.
Best answer by TDK

> GPIOA->MODER |= (1U<<1); //PA0 alternate function

> TIM2->CCR2 = 500;

TIM2_CH2 is not on PA0 is, but TIM2_CH1 is.

Use CCR1 instead of CCR2.

Note that the period is (timer clock) / (PSC + 1) / (ARR + 1) so you don't quite have 50% duty cycle. Probably want PSC=7999, ARR=999, CCR1=500.

2 replies

TDK
TDKBest answer
March 8, 2022

> GPIOA->MODER |= (1U<<1); //PA0 alternate function

> TIM2->CCR2 = 500;

TIM2_CH2 is not on PA0 is, but TIM2_CH1 is.

Use CCR1 instead of CCR2.

Note that the period is (timer clock) / (PSC + 1) / (ARR + 1) so you don't quite have 50% duty cycle. Probably want PSC=7999, ARR=999, CCR1=500.

"If you feel a post has answered your question, please click ""Accept as Solution""."
Nick-
Nick-Author
Associate II
March 9, 2022

I didn't notice that the CH was wrong. I fix the code and now it works as expected. Thank you very much!