当前位置:   article > 正文

1-3 STM32F103按键中断(代码复制即可使用)_stm32f103c8t6外部中断

stm32f103c8t6外部中断

外部中断的配置流程如下:

        1:根据原理图初始化按键的GPIO和LED的GPIO。

        2:编写相应的中断服务函数。

 LED初始化代码如下:

  1. #include "led.h"
  2. void Led_Init(void)
  3. {
  4. GPIO_InitTypeDef Led_InitStructure;
  5. RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
  6. Led_InitStructure.GPIO_Pin = GPIO_Pin_13;
  7. Led_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
  8. Led_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
  9. GPIO_Init(GPIOC, &Led_InitStructure);
  10. }
  11. void Led_Open(void)
  12. {
  13. GPIO_ResetBits(GPIOC, GPIO_Pin_13);
  14. }
  15. void Led_Close(void)
  16. {
  17. GPIO_SetBits(GPIOC, GPIO_Pin_13);
  18. }

led.h如下:

  1. #include "stm32f10x.h"
  2. void Led_Init(void);
  3. void Led_Open(void);
  4. void Led_Close(void);

按键初始化代码如下:

  1. #include "key.h"
  2. void Key_Init(void)
  3. {
  4. GPIO_InitTypeDef Key_InitStructure;
  5. RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE); //只要不作为普通IO口使用就要打开AFIO时钟
  6. Key_InitStructure.GPIO_Pin = GPIO_Pin_0;
  7. Key_InitStructure.GPIO_Mode = GPIO_Mode_IPU; //配置为上拉输入
  8. GPIO_Init(GPIOA, &Key_InitStructure);
  9. }

key.h如下:

  1. #include "stm32f10x.h"
  2. void Key_Init(void);

外部中断EXTI的配置代码如下:

  1. #include "exti.h"
  2. uint8_t flag = 0;
  3. void Exti_Init(void)
  4. {
  5. NVIC_InitTypeDef Nvic_InitStructure;
  6. EXTI_InitTypeDef Exti_InitStructure;
  7. NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
  8. Nvic_InitStructure.NVIC_IRQChannel = EXTI0_IRQn; //设置指定通道
  9. Nvic_InitStructure.NVIC_IRQChannelCmd = ENABLE; //使能IRQ通道的中断
  10. Nvic_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //设置抢占优先级
  11. Nvic_InitStructure.NVIC_IRQChannelSubPriority = 1; //设置子优先级
  12. NVIC_Init(&Nvic_InitStructure);
  13. Exti_InitStructure.EXTI_Line = EXTI_Line0; //选择使能外部线路
  14. Exti_InitStructure.EXTI_LineCmd = ENABLE; //定义选中线路的状态
  15. Exti_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; //设置EXTI线路为中断请求
  16. Exti_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising_Falling; //设置输入线路上升沿和下降沿为中断请求
  17. EXTI_Init(&Exti_InitStructure);
  18. }
  19. void EXTI0_IRQHandler(void) //中断服务函数
  20. {
  21. if(EXTI_GetITStatus(EXTI_Line0) != RESET) //判断是否发生中断
  22. {
  23. flag = 1 - flag; //实现标志位翻转
  24. }
  25. EXTI_ClearITPendingBit(EXTI_Line0); //清除中断标志位
  26. }
  1. #include "stm32f10x.h"
  2. extern uint8_t flag;
  3. void Exti_Init(void);

main.c代码如下:

  1. #include "stm32f10x.h"
  2. #include "led.h"
  3. #include "exti.h"
  4. #include "key.h"
  5. int main()
  6. {
  7. Led_Init();
  8. Exti_Init();
  9. Key_Init();
  10. while(1)
  11. {
  12. if(flag)
  13. {
  14. Led_Open();
  15. }
  16. else
  17. {
  18. Led_Close();
  19. }
  20. }
  21. }

这次外部中断实现的功能主要是按下按键LED灯的状态翻转。

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号