[Blue Bridge Cup Embedded] [HAL Library] Eight, timer interrupt

Hits: 0

Experiment introduction

It is no exaggeration to say that the timer is the soul of the microcontroller, so knowledge about the timer must be mastered. The timer is used to count. When the frequency of the timer is configured, the frequency is counted. We generally need to cooperate with the interrupt to operate. When the timer counts to the value we want, enter the interrupt function and execute We have written operations. There are many powerful bloggers who have written very well about the introduction of timers. I will not describe them here. This article only introduces how to use them. In this experiment, the timer interrupt is used to realize that eight LEDs light up and down in different directions in turn every 100ms.
Attachment: Timer period calculation formula:
T = (arr+1) * (PSC+1) / Tck
where TCK is the clock frequency, PSC is the clock prescale factor, and arr is the auto-reload value.
Example: Tck = 80MHz, PSC = 80 – 1, arr = 10000 – 1, then the timer period = 80 * 10000 / 80000000 = 10ms, if the interrupt is enabled, it will enter the interrupt function every 10ms.

STM32CubeMX configuration

Clock, the clock tree configuration is no longer described.
Timer configuration:
GPIO configuration: just
generate the project.


Initial code before execution:

    // Turn on the latch and turn off the 8 leds
    GPIOC->ODR = 0xFFFF;

    HAL_TIM_Base_Start_IT(&htim1); // Enable TIM1 interrupt 
  /* USER CODE END 2 */

Interrupt callback function (located below the main function):

void  HAL_TIM_PeriodElapsedCallback (TIM_HandleTypeDef *htim)
     // The static keyword means that this value is only defined for the first time, such as: 0, and subsequent interrupts will not be redefined 
    static  uint8_t counter = 0 , i = 0 , dir = 0 ;
     static  uint16_t led = 0x0001 ;

    if (htim->Instance == TIM1) // Determine which timer generated the interrupt
        // When the count is 10, that is, it counts for 100ms, and enters the execution operation
        if(counter == 10)
            counter = 0 ; // the counter is cleared and counted 
            again GPIOC->ODR = ~(led << ( 8 + i)); // the register controls the on and off of the led

        // Each time the value of i corresponds to a certain LED, dir is the direction in which the LEDs are turned on in turn 
        if (dir == 0 ) // ld1 -> ld8
            if(i == 7)
                    dir = 1;
        else // dir = 1 , ld8 -> ld1
            if(i == 0)
                    dir = 0;
        HAL_TIM_Base_Start_IT(&htim1); // After executing the interrupt program, start the interrupt again

Note: We all write the interrupt function in the interrupt callback function, which is the same as the original serial port interrupt.

You may also like...

Leave a Reply

Your email address will not be published.