cancel
Showing results for 
Search instead for 
Did you mean: 

Count number of pulses on TIM1 input on STM32G031

Stastny.Petr
Associate III

Hello,

I have STM32G031 and I want to use PA8 pin (TIM1_CH1) to count pulses. My idea is to read number of counted pulses every 1 second and reset counter to 0.

 

void TIM1_Init(void)
{
    // Enable TIM1 clock
    RCC->APBENR2 |= RCC_APBENR2_TIM1EN;

    // Configure TIM1 as external counter on TI1 (PA8)
    TIM1->ARR = 0xFFFF; // Set auto-reload register to maximum value
    TIM1->PSC = 0; // No prescaler

    TIM1->SMCR &= ~TIM_SMCR_SMS_Msk;
    TIM1->SMCR |= TIM_SMCR_SMS_2; // External clock mode 1
    TIM1->SMCR &= ~TIM_SMCR_TS_Msk;
    TIM1->SMCR |= TIM_SMCR_TS_2 | TIM_SMCR_TS_0; // TI1FP1 as trigger
    TIM1->CCMR1 &= ~TIM_CCMR1_CC1S_Msk;
    TIM1->CCMR1 |= TIM_CCMR1_CC1S_0; // CC1 channel is configured as input, IC1 is mapped on TI1
    TIM1->CCER &= ~TIM_CCER_CC1P; // Capture/Compare 1 output polarity: non-inverted

    // Enable counter
    TIM1->CR1 |= TIM_CR1_CEN;
}


and every 1 second reset:

        // Read counter value from TIM1
        pulse_count = TIM1->CNT;

        // Reset TIM1 counter
        TIM1->CNT = 0;

 

The result when no input is not zero but some big number. To you see where is problem?

 

There should we the easy way but does not work:

StastnyPetr_0-1722952977228.png

 

1 ACCEPTED SOLUTION

Accepted Solutions
Stastny.Petr
Associate III

Solved, this is wrong settings: 

TIM1->SMCR |= TIM_SMCR_SMS_2; // External clock mode 1

This is correct:

TIM1->SMCR |= TIM_SMCR_SMS_2 | TIM_SMCR_SMS_1 | TIM_SMCR_SMS_0; // External clock mode 2 (SMS = 111)

 

View solution in original post

1 REPLY 1
Stastny.Petr
Associate III

Solved, this is wrong settings: 

TIM1->SMCR |= TIM_SMCR_SMS_2; // External clock mode 1

This is correct:

TIM1->SMCR |= TIM_SMCR_SMS_2 | TIM_SMCR_SMS_1 | TIM_SMCR_SMS_0; // External clock mode 2 (SMS = 111)