课程实验要求:通过配置外部中断实现按键按下,LED灯的状态由闪烁->保持->点亮->熄灭如此循环
步骤:配置好中断、LED的GPIO口、通过中断服务函数改变标志位,在主循环里判断标志位的变量。
1、EXTI.c文件
#include "stm32f10x.h" // Device header
#include "LED.h"
void MyEXTI_Init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE); //开启AFIO时钟
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOE, &GPIO_InitStructure);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOE, GPIO_PinSource4); //实际操作AFIO
EXTI_InitTypeDef EXTI_InitStructure; //外部中断配置
EXTI_InitStructure.EXTI_Line = EXTI_Line4;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
EXTI_Init(&EXTI_InitStructure);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //配置中断模式,一整个代码只用配置一次
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = EXTI4_IRQn;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_Init(&NVIC_InitStructure);
}
extern uint8_t mode;
void EXTI4_IRQHandler(void)
{
if(EXTI_GetITStatus(EXTI_Line4) == SET)
{
for(int i = 0; i < 1000; i ++);
if(GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_4) == RESET)
{
mode++;
if(mode > 4)
mode = 1;
}
}
EXTI_ClearITPendingBit(EXTI_Line4);
}
2、LED.c文件
#include "stm32f10x.h" // Device header
void LED_Init(void) //LED初始化函数
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOG, ENABLE); //APB2外设时钟控制(接在GPIOA上,使能)
GPIO_InitTypeDef GPIO_InitStructure; //定义一个结构体变量
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //GPIO模式:推挽输出
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_8; //用到GPIO1、2号口
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //GPIO的速度
GPIO_Init(GPIOG,&GPIO_InitStructure); //初始化GPIOA外设,结构体变量名取地址(地址传递)
GPIO_SetBits(GPIOG, GPIO_Pin_6 | GPIO_Pin_8); //GPIOA 1、2口设置为高电平
}
void LED1_ON(void)
{
GPIO_ResetBits(GPIOG,GPIO_Pin_6);
}
void LED1_OFF(void)
{
GPIO_SetBits(GPIOG,GPIO_Pin_6);
}
void LED1_Turn(void)
{
if(GPIO_ReadInputDataBit(GPIOG, GPIO_Pin_6)==0) //读取现在的输出值
{
GPIO_SetBits(GPIOG, GPIO_Pin_6);
}
else
{
GPIO_ResetBits(GPIOG,GPIO_Pin_6);
}
}
void LED2_ON(void)
{
GPIO_ResetBits(GPIOG,GPIO_Pin_8);
}
void LED2_OFF(void)
{
GPIO_SetBits(GPIOG,GPIO_Pin_8);
}
void LED2_Turn(void)
{
if(GPIO_ReadInputDataBit(GPIOG, GPIO_Pin_8)==0)
{
GPIO_SetBits(GPIOG, GPIO_Pin_8);
}
else
{
GPIO_ResetBits(GPIOG,GPIO_Pin_8);
}
}
3、main.c文件
#include "stm32f10x.h" // Device header
#include "LED.h"
#include "MyEXTI.h"
uint8_t mode;
int main(void)
{
LED_Init();
MyEXTI_Init();
while(1)
{
switch(mode)
{
case 1:
LED1_Turn();
break;
case 2:
break;
case 3:
LED1_ON();
break;
case 4:
LED1_OFF();
break;
}
}
}
.h文件自己添加或不用也可以。