STM32F10x timer interrupt init

Процедура инициализации и обработки прерывания по переполнению от таймера.

void TIM2_IRQHandler(void)
{
    static char led_state = 0;
    if(TIM2->SR & TIM_SR_UIF)
    {
        if(led_state)
            GPIOB->BSRR = GPIO_Pin_9;
        else
            GPIOB->BRR = GPIO_Pin_9;
        led_state = ~led_state;
        // TIM2->SR &= ~TIM_SR_UIF;
    }
    TIM2->SR = 0;
}

void initTim2(void)
{
    RCC->APB1ENR |= RCC_APB1Periph_TIM2;

    TIM2->CR1 = /* TIM_CR1_DIR |*/ TIM_CR1_URS;
    TIM2->CR2 = 0;
    TIM2->CNT = 0;
    TIM2->PSC = 10000; // Clock prescaler;

    TIM2->ARR = 3600; // Auto reload value
    TIM2->SR = 0; // Clean interrups & events flag

    TIM2->DIER = TIM_DIER_UIE; // Enable update interrupts

    /* NVIC_SetPriority & NVIC_EnableIRQ defined in core_cm3.h */
    NVIC_SetPriority (TIM2_IRQn, (1<<__NVIC_PRIO_BITS) - 1); /* set Priority for Cortex-M0 System Interrupts */
    NVIC_EnableIRQ (TIM2_IRQn);

    TIM2->EGR = TIM_EGR_UG;
    TIM2->CR1 |= TIM_CR1_CEN; // Enable timer
}
 
comments powered by Disqus