top of page

Timerinterrupt im Sekundentakt generieren

In diesem Beispiel wird mit dem Timer2 ein Timerinterrupt generiert, welcher im Sekundentakt eine LED an PD15 toggelt.

Code

/* This example shows how you can use a timer interrupt.

 * In this case, the timer2 count up to 1000 and generate an IRQ which toggles a LED every second.

 * The clock frequency of the internal oscillator = 16MHz

 */

 

#include <stm32f4xx.h>

 

void TIM2_IRQHandler(void)          // IRQ-Handler timer2

{

    if (TIM2->SR & TIM_SR_UIF)       // flash on update event

        GPIOD->ODR ^= (1 << 15);   // Turn GPIOD pin15 (blue LED) ON in GPIO port output data register

 

    TIM2->SR = 0x0;              // reset the status register

}

 

int main(void)

{

    RCC -> AHB1ENR |= RCC_AHB1ENR_GPIODEN;       // Enable CLK for PortD in peripheral clock register (RCC_AHB1ENR)

    RCC -> APB1ENR |= RCC_APB1ENR_TIM2EN;        // enable TIM2 clock

 

    GPIOD -> MODER |= (1<<30);                 // Set pin 15 (blue LED)to be general purpose output in GPIO port mode register

 

    NVIC -> ISER[0] |= 1<< (TIM2_IRQn);        // enable the TIM2 IRQ

 

    TIM2 -> PSC = 16000;                         // prescaler = 16000 (timer2 clock = 16MHz clock / 16000 = 1000Hz)

    TIM2 -> DIER |= TIM_DIER_UIE;                // enable update interrupt

    TIM2 -> ARR = 1000;                      // count to 1000 (autoreload value 1000) --> overflow every 1 second

    TIM2 -> CR1 |= TIM_CR1_ARPE | TIM_CR1_CEN;   // autoreload on, counter enabled

    TIM2 -> EGR = 1;                             // trigger update event to reload timer registers

 

    while(1)

    {

    }

}

bottom of page