Here is an example code that uses timers, external interrupts, and HAL library functions to blink the built-in LED for 1.5 seconds when the button is pressed once, and turns off when the button is pressed again. This code assumes that the button is connected to GPIO pin PA0 and the LED is connected to GPIO pin PA5.

#include "main.h"

TIM_HandleTypeDef htimer2;
GPIO_InitTypeDef GPIO_InitStruct;

int led_state = 0;
int button_state = 0;

void SystemClock_Config(void);
void TIM2_Init(void);
void GPIO_Init(void);

int main(void) {
  HAL_Init();
  SystemClock_Config();
  GPIO_Init();
  TIM2_Init();

  while (1) {
    button_state = HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0);
    if (button_state == GPIO_PIN_SET) {
      if (led_state == 0) {
        HAL_TIM_Base_Start_IT(&htimer2);
        led_state = 1;
      } else {
        HAL_TIM_Base_Stop_IT(&htimer2);
        HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_RESET);
        led_state = 0;
      }
    }
  }
}

void SystemClock_Config(void) {
  RCC_OscInitTypeDef RCC_OscInitStruct;
  RCC_ClkInitTypeDef RCC_ClkInitStruct;

  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = 16;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
    Error_Handler();
  }

  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK) {
    Error_Handler();
  }
}

void TIM2_Init(void) {
  htimer2.Instance = TIM2;
  htimer2.Init.Prescaler = 64;
  htimer2.Init.CounterMode = TIM_COUNTERMODE_UP;
  htimer2.Init.Period = 1500; // 1.5 seconds
  htimer2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  if (HAL_TIM_Base_Init(&htimer2) != HAL_OK) {
    Error_Handler();
  }
}

void GPIO_Init(void) {
  __HAL_RCC_GPIOA_CLK_ENABLE();

  GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_5;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
  if (htim->Instance == TIM2) {
    HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5);
  }
}

void Error_Handler(void) {
  while (1) {
    // Handle error
  }
}

Note: This code assumes that you have properly configured the necessary startup files, header files, and linker settings for your specific microcontroller and development environment.

STM32 Timer and Interrupt Based LED Blink with Button Control (No Delay Function)

原文地址: http://www.cveoy.top/t/topic/n3Z 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录