重点:外部中断
代码:
main.c:
#include "stm32f10x.h"
#include "stm32f10x_exti.h"
#include "stm32f10x_rcc.h"
#include "misc.h"
void RCC_Configuration(void);
void GPIO_Configuration(void);
void NVIC_Configuration(void);
void Delay(__IO uint32_t nCount);
void Key_scan(void);
unsigned char _it0 = 0, num = 0;
int main()
{
unsigned char b = 0;
RCC_Configuration();
NVIC_Configuration();
GPIO_Configuration();
while(1){
Key_scan();
if(num == 2 && b == 0){
GPIO_SetBits(GPIOD, GPIO_Pin_2);
b = 1;
}else if(num == 2 && b == 1){
GPIO_ResetBits(GPIOD, GPIO_Pin_2);
b = 0;
}
}
}
void Key_scan()
{
num = 0;
if(_it0 == 2){
if(GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_4) == 0){
Delay(0xffff);//GPIO_ReadInputDataBit()函数读取PC4引脚的状态
if(GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_4) == 0){
while(GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_4) == 0);
num = 2;
}
}
_it0 = 0;
}
}
void Delay(__IO uint32_t nCount)
{
for(; nCount != 0; nCount--);
}
void RCC_Configuration(void)
{
SystemInit();
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);//打开AFOI时钟,使用复用I/O功能
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD, ENABLE);
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOD, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//PC4被复用做中断
GPIO_Init(GPIOC, &GPIO_InitStructure);
}
void NVIC_Configuration(void)//配置中断控制器
{
NVIC_InitTypeDef NVIC_InitStructure;
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
NVIC_InitStructure.NVIC_IRQChannel = EXTI4_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x02;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x03;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOC, GPIO_PinSource4);
EXTI_InitStructure.EXTI_Line = EXTI_Line4;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
}
stm32f10x_it.c:
#include "stm32f10x_it.h"
#include "stm32f10x_exti.h"
#include "stm32f10x_rcc.h"
#include "misc.h"
extern unsigned char _it0;
void EXTI4_IRQHandler(void)
{
if(EXTI_GetITStatus(EXTI_Line4) != RESET){
_it0 = 2;
EXTI_ClearITPendingBit(EXTI_Line4);
}
}
小结:
1,I/O口与中断线有确定的对应关系
2,外部中断要将GPIO管脚设置成浮空输入模式