STM32F4 HAL库控制按键控制LED灯闪烁的代码示例:
#include "stm32f4xx_hal.h"
void SystemClock_Config(void);
void Error_Handler(void);
GPIO_InitTypeDef GPIO_InitStruct;
EXTI_HandleTypeDef EXTI_InitStruct;
void EXTI15_10_IRQHandler(void);
int main(void)
{
HAL_Init();
SystemClock_Config();
__HAL_RCC_GPIOA_CLK_ENABLE(); //使能GPIOA时钟
GPIO_InitStruct.Pin = GPIO_PIN_5; //设置PA5引脚
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; //输出模式
GPIO_InitStruct.Pull = GPIO_NOPULL; //无上下拉电阻
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; //高速模式
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); //初始化GPIOA
__HAL_RCC_GPIOC_CLK_ENABLE(); //使能GPIOC时钟
GPIO_InitStruct.Pin = GPIO_PIN_13; //设置PC13引脚
GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING; //下降沿触发中断模式
GPIO_InitStruct.Pull = GPIO_PULLUP; //上拉电阻
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; //高速模式
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); //初始化GPIOC
HAL_NVIC_SetPriority(EXTI15_10_IRQn, 0, 1); //设置中断优先级
HAL_NVIC_EnableIRQ(EXTI15_10_IRQn); //使能中断
while (1)
{
HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5); //翻转PA5引脚状态
HAL_Delay(500); //延时500ms
}
}
void EXTI15_10_IRQHandler(void)
{
HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_13); //处理中断
}
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
if (GPIO_Pin == GPIO_PIN_13)
{
HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5);翻转PA5引脚状态
}
}
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Configure the main internal regulator output voltage
*/
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 336;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 7;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
{
Error_Handler();
}
}
void Error_Handler(void)
{
`
在上面的示例中,我们使用PA5引脚与PC13引脚来控制LED灯闪烁。当按下PC13引脚时,会触发中断,并通过`HAL_GPIO_EXTI_Callback()`函数将PA5引脚状态翻转。
注意,这只是一个示例,具体实现可能会因为硬件版本或其他因素而有所不同。