Skip to content

Yubin-dev0/STM32_TimerInterrupt_LED_Toggle

Repository files navigation

STM32 Timer Interrupt LED Toggle with Button

English Description

This project demonstrates using Timer Interrupt (TIM2) and External Interrupt (EXTI13) on an STM32 NUCLEO-F103RB.

  • LED (PA5) toggles every 0.5 s by default (via TIM2 update event).
  • Button (PC13) is connected to EXTI; each press switches the timer period between 0.5 s and 1.0 s.
  • Implemented with STM32CubeIDE (HAL).

Note on timing: With the current clock config (PLL 64 MHz, APB1/2 as in the repo) and PSC=7199, timer tick ≈ 8,888.9 Hz, so ARR ≈ 4443 for 0.5 s and 8888 for 1.0 s.
If you prefer a neat 10 kHz tick, set PSC=6399 and use ARR 4999/9999.


한국어 설명

이 프로젝트는 STM32 NUCLEO-F103RB에서 TIM2 타이머 인터럽트와 **EXTI(PC13 버튼)**를 결합해

  • 기본은 0.5초마다 LED(PA5)를 토글하고,
  • 버튼을 누를 때마다 0.5초 ↔ 1초로 주기를 전환하는 예제입니다.
    개발환경은 STM32CubeIDE + HAL입니다.

팁: Nucleo 보드의 B1 버튼(PC13)은 Pull-up 상태에서 누르면 GND로 떨어지므로, EXTI 트리거를 Falling으로 설정하세요.


Demo Video

▶️ YouTube Demo


핵심 코드 (Core Code Snippet)

// main.c (USER CODE BEGIN 2)
HAL_NVIC_SetPriority(TIM2_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(TIM2_IRQn);
HAL_TIM_Base_Start_IT(&htim2);   // Start TIM2 interrupt
// LED toggle on timer interrupt
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    if (htim->Instance == TIM2)
    {
        HAL_GPIO_TogglePin(LD2_GPIO_Port, LD2_Pin);
    }
}
// Button interrupt: toggle between 0.5 s and 1.0 s
volatile uint8_t  g_half_sec    = 1;  // 1: 0.5s, 0: 1.0s
volatile uint32_t g_last_btn_ms = 0;

// For current 64MHz/PSC=7199 (≈8888.9 Hz tick)
#define ARR_0P5S  (4443)   // round(0.5 * 8888.9) - 1
#define ARR_1P0S  (8888)   // round(1.0 * 8888.9) - 1

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
    if (GPIO_Pin == GPIO_PIN_13)
    {
        uint32_t now = HAL_GetTick();
        if (now - g_last_btn_ms < 200) return; // debounce
        g_last_btn_ms = now;

        g_half_sec = !g_half_sec;
        uint32_t new_arr = g_half_sec ? ARR_0P5S : ARR_1P0S;

        __HAL_TIM_SET_AUTORELOAD(&htim2, new_arr);
        __HAL_TIM_SET_COUNTER(&htim2, 0); // restart the period immediately
    }
}


//If you switch to a 10 kHz timer tick: PSC=6399, use ARR_0P5S=4999, ARR_1P0S=9999.

About

STM32 TIM2 interrupt + EXTI13 (button) to switch LED period (0.5s ↔ 1s)

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages