写一段独立按键产生的高低电平作为中断的信号源,中断方式点亮和熄灭 L0 发光二极管的代码
时间: 2023-05-27 13:05:57 浏览: 89
以下是基于STM32F103C8T6的代码实现:
先定义按键引脚和LED引脚:
```
#define KEY_PIN GPIO_Pin_0
#define KEY_PORT GPIOA
#define LED_PIN GPIO_Pin_0
#define LED_PORT GPIOB
```
初始化按键引脚为输入,上拉模式:
```
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = KEY_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(KEY_PORT, &GPIO_InitStructure);
```
初始化LED引脚为输出,低电平:
```
GPIO_InitStructure.GPIO_Pin = LED_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_PORT, &GPIO_InitStructure);
GPIO_SetBits(LED_PORT, LED_PIN);
```
定义中断服务函数:
```
void EXTI0_IRQHandler(void)
{
if(EXTI_GetITStatus(EXTI_Line0) != RESET)
{
GPIO_WriteBit(LED_PORT, LED_PIN, (BitAction)(1 - GPIO_ReadOutputDataBit(LED_PORT, LED_PIN)));
EXTI_ClearITPendingBit(EXTI_Line0);
}
}
```
初始化外部中断0:
```
NVIC_InitTypeDef NVIC_InitStructure;
EXTI_InitTypeDef EXTI_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
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_Falling;
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);
```
在主循环中不断检测按键状态:
```
while(1)
{
if(GPIO_ReadInputDataBit(KEY_PORT, KEY_PIN) == RESET)
{
GPIO_WriteBit(LED_PORT, LED_PIN, (BitAction)(1 - GPIO_ReadOutputDataBit(LED_PORT, LED_PIN)));
delay_ms(100);
}
}
```
其中,delay_ms() 函数为延时函数,可以使用 SysTick 系统滴答定时器实现。
阅读全文