STM32微控制器之外部中断/事件控制器EXTI的使用方法

STM32微控制器的外部中断/事件控制器(External Interrupt/Event Controller,EXTI)管理了控制器的中断/事件线。每个中断/事件线都对应有一个边沿检测器,可以实现输入信号的上升沿检测和下降沿的检测。EXTI可以实现对每个中断/事件线进行单独配置,可以单独配置为中断或者事件,以及触发事件的属性。

实验程序:按键产生中断,控制LED灯开关状态的反转。

一、配置EXTI

void EXTI0_Config(void)
{
	EXTI_InitTypeDef EXTI_InitStructure;
	GPIO_InitTypeDef GPIO_InitStructure;
	NVIC_InitTypeDef NVIC_InitStructure;
	
	// Enable GPIOC clock
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
	
	// Configure PC.00 pin as input floating
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
	GPIO_Init(GPIOC, &GPIO_InitStructure);
	
	// Enable AFIO clock
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
	
	// Connect EXTI0 Line to PC.00 pin
	GPIO_EXTILineConfig(GPIO_PortSourceGPIOC, GPIO_PinSource0);
	
	// Configure EXTI0 line
	EXTI_InitStructure.EXTI_Line = EXTI_Line0;
	EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
	EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
	EXTI_InitStructure.EXTI_LineCmd = ENABLE;
	EXTI_Init(&EXTI_InitStructure);
	
	// Enable and set EXTI0 Interrupt to the lowest priority
	NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x0F;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x0F;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);
}

二、配置LED

void LED_Config(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	
	// Enable GPIOB clock
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
	
	// Configure PB.0~15 pins as output push-pull
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_All;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
	GPIO_Init(GPIOB, &GPIO_InitStructure);
}

三、中断处理程序

void EXTI0_IRQHandler(void)
{
	if(EXTI_GetITStatus(EXTI_Line0) != RESET)
	{
		// Toggle LED
		GPIOB->ODR ^= GPIO_Pin_All;
		
		// Clear the  EXTI line 0 pending bit
		EXTI_ClearITPendingBit(EXTI_Line0);
	}
}

四、主程序

#include "stm32f10x.h"
#include "bsp_led.h"
#include "bsp_exti.h"

int main(void)
{
	// Configure LED
	LED_Config();
	
	// Configure EXTI
	EXTI0_Config();
	
	while(1)
	{
		__asm("nop");
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *