以下是为您在上述代码基础上增加 B1 引脚按键控制 LED 停止闪烁的修改代码: ```c #include "stm32f10x.h" #define LED_PIN 13 #define BUTTON_PIN 1 void delay(uint32_t count) { while(count--); } int main(void) { GPIO_InitTypeDef GPIO_InitStructure; // 使能 GPIO 时钟 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB, ENABLE); // 配置 LED 引脚(PA13)为推挽输出 GPIO_InitStructure.GPIO_Pin = (1 << LED_PIN); GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); // 配置按键引脚(PB1)为上拉输入 GPIO_InitStructure.GPIO_Pin = (1 << BUTTON_PIN); GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; GPIO_Init(GPIOB, &GPIO_InitStructure); uint8_t isButtonPressed = 0; while (1) { if ((GPIOB->IDR & (1 << BUTTON_PIN)) == 0 && isButtonPressed == 0) { isButtonPressed = 1; } else if ((GPIOB->IDR & (1 << BUTTON_PIN))!= 0 && isButtonPressed == 1) { isButtonPressed = 0; } if (isButtonPressed == 0) { GPIOA->ODR ^= (1 << LED_PIN); delay(0xFFFFF); } } } ``` 以下是三个改进建议: 1. 对代码添加更多注释,以提高代码的可理解性。 2. 可以将按键检测和 LED 控制部分的代码封装成独立的函数,以增强代码的模块化。 3. 考虑使用中断来处理按键事件,提高程序的响应性能。 [2024-12-26 10:48:58 | AI写代码神器 | 503点数解答]