Skip to main content
JAlca
Associate III
November 17, 2019
Solved

TIM2, using TI2 external clock problem (STM32F303CCT6)

  • November 17, 2019
  • 2 replies
  • 725 views

Hi all!,

I want to use TIM2 to count tghe times a button is pressed.

I connected the button to PA1, with a pulldown resistor. When the button is pressed, a hign pulse enters to PA1.

I run this program, and read the TIM2->CNT, but it doesnt move.

This is the program I'm testing. Please, any advices?

 RCC->AHBENR |= RCC_AHBENR_GPIOAEN;
 RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;
 
	//PA1 Alternate Function.
	GPIOA->MODER &= ~GPIO_MODER_MODER1_0;
	GPIOA->MODER |= GPIO_MODER_MODER1_1;
 
	//Alternate Function 3 = TI2
	GPIOA->AFR[0] |= 0x00000030;
	GPIOA->AFR[0] &= 0xFFFFFF3F;
	
	TIM2->CR1 = RESET;
	TIM2->CCMR1 = RESET;
	TIM2->CCER = RESET; //CC2E MUST BE 0 IN ORDER TO CHANGE CC2S
	TIM2->SMCR = RESET;
 
	//CC2 input, mapped on TI2
	TIM2->CCMR1 |= TIM_CCMR1_CC2S_1;
	
	//Select external clock mode 1
	TIM2->SMCR |= TIM_SMCR_SMS_0 | TIM_SMCR_SMS_1 | TIM_SMCR_SMS_2; 
 
	//TI2FP2
	TIM2->SMCR |= TIM_SMCR_TS_1 | TIM_SMCR_TS_2;
 
	TIM2->CCER |= TIM_CCER_CC2E; //Capture compare enable register
 
 
 
	//TIM2->PSC = (SystemCoreClock / 1000) - 1; //Milisegundos
	TIM2->ARR = 30;
	TIM2->EGR = RESET;
	TIM2->EGR |= TIM_EGR_UG;
 
	TIM2->CR1 |= TIM_CR1_CEN;

This topic has been closed for replies.
Best answer by waclawek.jan

> TIM2->CCMR1 |= TIM_CCMR1_CC2S_1;

This in case of CCMR2.CC2S sets it to 0b01 i.e. mapping IC2 to TI1, which is not what you want.

Exactly because of this, when it comes to multi-bit values, I prefer an expression where the value (or a suitably called macro) actually can be seen, e.g.

TIM2->CCMR1 = (0b01 << TIM_CCMR1_CC2S_Pos)

Also - althought this has no impact on the function - you don't need to clear, and don't need to |= to EGR - it's not a "normal" register, just simply write the pattern into it

TIM2->EGR = TIM_EGR_UG.

JW

2 replies

waclawek.jan
waclawek.janBest answer
Super User
November 17, 2019

> TIM2->CCMR1 |= TIM_CCMR1_CC2S_1;

This in case of CCMR2.CC2S sets it to 0b01 i.e. mapping IC2 to TI1, which is not what you want.

Exactly because of this, when it comes to multi-bit values, I prefer an expression where the value (or a suitably called macro) actually can be seen, e.g.

TIM2->CCMR1 = (0b01 << TIM_CCMR1_CC2S_Pos)

Also - althought this has no impact on the function - you don't need to clear, and don't need to |= to EGR - it's not a "normal" register, just simply write the pattern into it

TIM2->EGR = TIM_EGR_UG.

JW

JAlca
JAlcaAuthor
Associate III
November 17, 2019

Thank you man!

You're a valuable member of this forum.