赞
踩
外部中断的配置流程如下:
1:根据原理图初始化按键的GPIO和LED的GPIO。
2:编写相应的中断服务函数。
LED初始化代码如下:
- #include "led.h"
-
- void Led_Init(void)
- {
- GPIO_InitTypeDef Led_InitStructure;
-
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
-
- Led_InitStructure.GPIO_Pin = GPIO_Pin_13;
- Led_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
- Led_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
- GPIO_Init(GPIOC, &Led_InitStructure);
- }
-
- void Led_Open(void)
- {
- GPIO_ResetBits(GPIOC, GPIO_Pin_13);
- }
-
- void Led_Close(void)
- {
- GPIO_SetBits(GPIOC, GPIO_Pin_13);
- }
led.h如下:
- #include "stm32f10x.h"
-
- void Led_Init(void);
- void Led_Open(void);
- void Led_Close(void);
按键初始化代码如下:
- #include "key.h"
-
- void Key_Init(void)
- {
- GPIO_InitTypeDef Key_InitStructure;
-
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE); //只要不作为普通IO口使用就要打开AFIO时钟
-
- Key_InitStructure.GPIO_Pin = GPIO_Pin_0;
- Key_InitStructure.GPIO_Mode = GPIO_Mode_IPU; //配置为上拉输入
- GPIO_Init(GPIOA, &Key_InitStructure);
- }
key.h如下:
- #include "stm32f10x.h"
-
- void Key_Init(void);
外部中断EXTI的配置代码如下:
- #include "exti.h"
-
- uint8_t flag = 0;
-
- void Exti_Init(void)
- {
- NVIC_InitTypeDef Nvic_InitStructure;
- EXTI_InitTypeDef Exti_InitStructure;
-
-
- NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
- Nvic_InitStructure.NVIC_IRQChannel = EXTI0_IRQn; //设置指定通道
- Nvic_InitStructure.NVIC_IRQChannelCmd = ENABLE; //使能IRQ通道的中断
- Nvic_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //设置抢占优先级
- Nvic_InitStructure.NVIC_IRQChannelSubPriority = 1; //设置子优先级
- NVIC_Init(&Nvic_InitStructure);
-
- Exti_InitStructure.EXTI_Line = EXTI_Line0; //选择使能外部线路
- Exti_InitStructure.EXTI_LineCmd = ENABLE; //定义选中线路的状态
- Exti_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; //设置EXTI线路为中断请求
- Exti_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising_Falling; //设置输入线路上升沿和下降沿为中断请求
- EXTI_Init(&Exti_InitStructure);
- }
-
- void EXTI0_IRQHandler(void) //中断服务函数
- {
- if(EXTI_GetITStatus(EXTI_Line0) != RESET) //判断是否发生中断
- {
- flag = 1 - flag; //实现标志位翻转
- }
- EXTI_ClearITPendingBit(EXTI_Line0); //清除中断标志位
- }
- #include "stm32f10x.h"
-
- extern uint8_t flag;
-
- void Exti_Init(void);
main.c代码如下:
- #include "stm32f10x.h"
- #include "led.h"
- #include "exti.h"
- #include "key.h"
-
- int main()
- {
- Led_Init();
- Exti_Init();
- Key_Init();
- while(1)
- {
- if(flag)
- {
- Led_Open();
- }
- else
- {
- Led_Close();
- }
- }
- }
这次外部中断实现的功能主要是按下按键LED灯的状态翻转。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。