以下是在您提供的代码基础上增加按键控制的修改代码: ```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; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB, ENABLE); // 使能 GPIOA 和 GPIOB 时钟 GPIO_InitStructure.GPIO_Pin = (1 << LED_PIN); // 配置 LED 引脚 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = (1 << BUTTON_PIN); // 配置按键引脚 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(GPIOB, &GPIO_InitStructure); while (1) { if (GPIO_ReadInputDataBit(GPIOB, BUTTON_PIN) == 0) // 检测按键是否按下 { GPIO_WriteBit(GPIOA, LED_PIN, GPIO_ReadOutputDataBit(GPIOA, LED_PIN)); // 保持 LED 状态 } else { GPIO_WriteBit(GPIOA, LED_PIN, 1); // LED 亮 delay(500000); GPIO_WriteBit(GPIOA, LED_PIN, 0); // LED 灭 delay(500000); } } } ``` 以下是三个改进建议: 1. 增加必要的注释,以提高代码的可读性。 2. 优化延时函数,使用系统的定时中断来实现更精确的延时。 3. 对按键的消抖处理,以避免按键误触发。 [2024-12-26 10:48:58 | AI写代码神器 | 472点数解答]