STM32每按下一次数字发生改LED灯闪烁一次,数字未改变则不发生改变变
时间: 2024-04-30 07:23:14 浏览: 106
化。以下是一个简单的示例代码,实现了按下数字按钮控制LED灯闪烁的功能。假设数字按钮输入为GPIO_Pin_0,LED输出为GPIO_Pin_1:
```
#include "stm32f10x.h"
int main(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
// 初始化GPIO口
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; // 按钮使用上拉输入模式
GPIO_Init(GPIOA, &GPIO_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_PriorityGroupConfig(NVIC_PriorityGroup_2);
NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
// 循环检测数字按钮状态
int prev_button_state = 1; // 上一次按钮状态
int led_state = 0; // LED当前状态
while (1)
{
int button_state = GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0);
if (button_state == 0 && prev_button_state == 1) // 按钮从未按到按下
{
led_state = 1 - led_state; // 反转LED状态
GPIO_WriteBit(GPIOA, GPIO_Pin_1, (led_state ? Bit_SET : Bit_RESET)); // 更新LED输出状态
}
prev_button_state = button_state;
}
}
void EXTI0_IRQHandler(void)
{
if (EXTI_GetITStatus(EXTI_Line0) != RESET)
{
EXTI_ClearITPendingBit(EXTI_Line0);
}
}
```
阅读全文