stm32f103rct6按键使用外部中断控制LED代码
时间: 2023-10-03 07:01:48 浏览: 118
下面是基于STM32F103RCT6的按键使用外部中断控制LED的代码:
```
#include "stm32f10x.h"
void EXTI0_IRQHandler(void) {
if (EXTI_GetITStatus(EXTI_Line0) != RESET) {
GPIO_WriteBit(GPIOB, GPIO_Pin_12, (BitAction)(1 - GPIO_ReadOutputDataBit(GPIOB, GPIO_Pin_12)));
EXTI_ClearITPendingBit(EXTI_Line0);
}
}
void initGPIO() {
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOA, GPIO_PinSource0);
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
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);
NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x00;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
int main(void) {
initGPIO();
while (1) {
// Loop
}
}
```
该代码的作用是,将按键连接到PA0引脚,将LED连接到PB12引脚。按下按键时,LED将切换状态。在代码中使用外部中断来检测按键的状态,并在触发中断时切换LED的状态。在初始化中,使用GPIO_Init函数来配置PB12为推挽输出模式,PA0为下拉输入模式。使用EXTI_Init函数来配置外部中断,以便在检测到按键状态变化时触发中断。在中断处理函数中,使用GPIO_WriteBit函数来切换LED的状态,并使用EXTI_ClearITPendingBit函数清除中断标志位。整个程序将被放在一个无限循环中,以便在触发中断后继续运行。
阅读全文