【STM32+HAL库】---- 按键中断控制LED

硬件开发板:STM32G0B1RET6
软件平台:cubemax+keil+VScode

1 新建cubemax工程

1.1 配置系统时钟树

image

1.2 配置相关GPIO引脚

①LED由PC13引脚控制
image
选择PA5引脚,GPIO_Output模式
image
GPIO模式配置:
image

②按键开关由PC13引脚控制
image
选择PC13引脚,GPIO_EXTIx模式,其中13表示13号中断线
image
GPIO模式配置:按键设置为下降沿触发中断(LED)
image

1.3 配置NVIC中断

勾上Enabled (G0系列相比于F1系列没有优先级Group配置)
image

1.4 导出工程

...略

2 中断处理流程

① main.c 中的 MX_GPIO_Init() 函数调用HAL库里的使能中断函数和设置中断优先级函数
image

② 在 HAL_NVIC_EnableIRQ() 中调用 NVIC_EnableIRQ()
image

③ 当触发中断时,处理器查表跳转到位于 stm32g0xx.it.c 里的中断服务程序 EXTIx_IRQHandler(void) 【这里的x指中断线】;中断服务程序 EXTIx_IRQHandler (void) 中调用外部中断通用处理函数HAL_GPIO_EXTI_IRQHandler (uint16_t GPIO_Pin) ,该函数作为HAL库提供的外部中断接口函数,参量为触发中断的引脚
image

④相比较于F系列,G0系列的HAL_GPIO_EXTI_IRQHandler (uint16_t GPIO_Pin)里所调用的中断回调函数分成了上升沿和下降沿两部分
G0系列:
image

F1/F4系列:
image

⑤在stm32g0xx.it.c 中重写对应类型的中断回调函数,并补全中断所需要执行的任务函数

3 代码

重写下降沿中断回调函数

//微秒级的延时
void delay_us(uint32_t delay_us)
{
  volatile unsigned int num;
  volatile unsigned int t;
  for (num = 0; num < delay_us; num++)
  {
    t = 11;
    while (t != 0)
    {
      t--;
    }
  }
}

//毫秒级的延时
void delay_ms(uint16_t delay_ms)
{
  volatile unsigned int num;
  for (num = 0; num < delay_ms; num++)
  {
    delay_us(1000);
  }
}

//下降沿回调函数
void HAL_GPIO_EXTI_Falling_Callback(uint16_t GPIO_Pin)
{
  if (GPIO_Pin==BUTTON_Pin)
  {
    delay_ms(20);     /*消抖*/
    if (GPIO_Pin==BUTTON_Pin)
    {
      HAL_GPIO_TogglePin(LED_GPIO_Port,LED_Pin);
      while (BUTTON_Pin==0);
    }
  }
}

补充

关于外部中断的嵌套可参考:https://blog.csdn.net/weixin_66509332/article/details/127748422

posted @ 2024-01-10 23:33  晚风也温柔  阅读(214)  评论(0编辑  收藏  举报