使用stm32标准库设定PA0和PA1为外部中断口,按键中断led1,led2
时间: 2024-05-07 07:16:12 浏览: 190
的状态翻转。
以下是使用stm32标准库设定PA0和PA1为外部中断口,按键中断led1,led2的状态翻转的示例代码:
```c
#include "stm32f10x.h"
#define LED1_PIN GPIO_Pin_8
#define LED2_PIN GPIO_Pin_9
#define BUTTON1_PIN GPIO_Pin_0
#define BUTTON2_PIN GPIO_Pin_1
void GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
// 配置LED引脚为推挽输出模式
GPIO_InitStructure.GPIO_Pin = LED1_PIN | LED2_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 配置按键引脚为浮空输入模式
GPIO_InitStructure.GPIO_Pin = BUTTON1_PIN | BUTTON2_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 配置PA0和PA1为外部中断口
GPIO_InitStructure.GPIO_Pin = BUTTON1_PIN | BUTTON2_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
void EXTI_Config(void)
{
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
// 配置PA0和PA1为外部中断
GPIO_EXTILineConfig(GPIO_PortSourceGPIOA, GPIO_PinSource0);
EXTI_InitStructure.EXTI_Line = EXTI_Line0;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOA, GPIO_PinSource1);
EXTI_InitStructure.EXTI_Line = EXTI_Line1;
EXTI_Init(&EXTI_InitStructure);
// 配置中断优先级
NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x01;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = EXTI1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x01;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x01;
NVIC_Init(&NVIC_InitStructure);
}
void EXTI0_IRQHandler(void)
{
if (EXTI_GetITStatus(EXTI_Line0) != RESET)
{
// 翻转LED1状态
GPIO_WriteBit(GPIOA, LED1_PIN, (BitAction)(1 - GPIO_ReadOutputDataBit(GPIOA, LED1_PIN)));
EXTI_ClearITPendingBit(EXTI_Line0);
}
}
void EXTI1_IRQHandler(void)
{
if (EXTI_GetITStatus(EXTI_Line1) != RESET)
{
// 翻转LED2状态
GPIO_WriteBit(GPIOA, LED2_PIN, (BitAction)(1 - GPIO_ReadOutputDataBit(GPIOA, LED2_PIN)));
EXTI_ClearITPendingBit(EXTI_Line1);
}
}
int main(void)
{
GPIO_Config();
EXTI_Config();
while (1);
return 0;
}
```
阅读全文