STM32 外部中断

第一步:配置时钟。 将用到的GPIO口时钟配置好,还要记得配置复用端口时钟AFIO

第二步:配置GPIO口。这里的GPIO配置是指与中断无关的,比如led灯之类

第三步:配置NVIC。  NVIC中设置中断优先级组,选择中断线,设置抢占与非抢占中断,并使能中断。

第四步:配置EXTI。  设置相应的GPIO口,模式设置为输入,将相应的GPIO口映射到对应的中断号。然后配置EXTI_InitTypeDef结构体。包括中短线,中断模式,触发模式,使能。

程序:

#include "stm32f10x.h"


#define GPIO_Key GPIO_Pin_10
#define GPIO_Led GPIO_Pin_2|GPIO_Pin_3|GPIO_Pin_4|GPIO_Pin_7
void ledTurnOnAll()
{
GPIO_ResetBits(GPIOD,GPIO_Led);
}


void RCCConfig()
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD | RCC_APB2Periph_GPIOB | RCC_APB2Periph_GPIOC,ENABLE);
}


void ledTurnOffAll()
{
GPIO_SetBits(GPIOD,GPIO_Led);
}


void GPIOConfig()
{
GPIO_InitTypeDef GPIO_InitStructure;

GPIO_InitStructure.GPIO_Pin = GPIO_Led;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOD,&GPIO_InitStructure);


}


void NVICConfig()
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
NVIC_InitStructure.NVIC_IRQChannel = EXTI15_10_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}


void EXTIConfig()
{
GPIO_InitTypeDef GPIO_InitStructure;
EXTI_InitTypeDef EXTI_InitStructure;

GPIO_InitStructure.GPIO_Pin = GPIO_Key;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOB,&GPIO_InitStructure);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_PinSource10); 
 

EXTI_InitStructure.EXTI_Line = EXTI_Line10;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
}
void EXTI15_10_IRQHandler()
{
static volatile int x = 0;


if(EXTI_GetITStatus(EXTI_Line10)!=RESET)//¼ì²âÖ¸¶¨µÄEXTI0Ïß·´¥·¢ÇëÇóÓë·ñ ·¢ÉúÖжÏʱ·µ»ØSET ÎÞÖжÏʱ·µ»ØRESET
  {
EXTI_ClearITPendingBit(EXTI_Line10);//Çå³ýEXTIÏß·¹ØÆðλ
if(x)
{
ledTurnOnAll();
x = 0;
}else{
ledTurnOffAll();
x = 1;
}
}  


}
int main()
{

RCCConfig();
GPIOConfig();
NVICConfig();
EXTIConfig();

while(1)
{

}
}

























你可能感兴趣的:(STM32 外部中断)