#include "main.h" // 定义流水灯引脚 #define LED_PORT GPIOA #define LED_PIN1 GPIO_PIN_0 #define LED_PIN2 GPIO_PIN_1 #define LED_PIN3 GPIO_PIN_2 #define LED_PIN4 GPIO_PIN_3 #define LED_PIN5 GPIO_PIN_4 #define LED_PIN6 GPIO_PIN_5 #define LED_PIN7 GPIO_PIN_6 #define LED_PIN8 GPIO_PIN_7 // 定义蜂鸣器引脚 #define BUZZER_PORT GPIOB #define BUZZER_PIN GPIO_PIN_0 // 定义按键引脚 #define BUTTON_PORT GPIOC #define BUTTON_PIN GPIO_PIN_13 // 定义流水灯状态 uint8_t led_state = 0; void SystemClock_Config(void); static void MX_GPIO_Init(void); int main(void) { HAL_Init(); // 初始化HAL库 SystemClock_Config(); // 配置系统时钟 MX_GPIO_Init(); // 初始化GPIO while (1) { // 检测按键是否按下(低电平有效) if (HAL_GPIO_ReadPin(BUTTON_PORT, BUTTON_PIN) == GPIO_PIN_RESET) { // 按键按下,控制流水灯和蜂鸣器 HAL_Delay(200); // 延时消抖 // 更新流水灯状态 led_state = (led_state + 1) % 8; // 清除所有流水灯 HAL_GPIO_WritePin(LED_PORT, LED_PIN1 | LED_PIN2 | LED_PIN3 | LED_PIN4 | LED_PIN5 | LED_PIN6 | LED_PIN7 | LED_PIN8, GPIO_PIN_RESET); // 点亮当前流水灯 switch (led_state) { case 0: HAL_GPIO_WritePin(LED_PORT, LED_PIN1, GPIO_PIN_SET); break; case 1: HAL_GPIO_WritePin(LED_PORT, LED_PIN2, GPIO_PIN_SET); break; case 2: HAL_GPIO_WritePin(LED_PORT, LED_PIN3, GPIO_PIN_SET); break; case 3: HAL_GPIO_WritePin(LED_PORT, LED_PIN4, GPIO_PIN_SET); break; case 4: HAL_GPIO_WritePin(LED_PORT, LED_PIN5, GPIO_PIN_SET); break; case 5: HAL_GPIO_WritePin(LED_PORT, LED_PIN6, GPIO_PIN_SET); break; case 6: HAL_GPIO_WritePin(LED_PORT, LED_PIN7, GPIO_PIN_SET); break; case 7: HAL_GPIO_WritePin(LED_PORT, LED_PIN8, GPIO_PIN_SET); break; } // 蜂鸣器发声 HAL_GPIO_WritePin(BUZZER_PORT, BUZZER_PIN, GPIO_PIN_SET); HAL_Delay(100); // 蜂鸣器发声100ms HAL_GPIO_WritePin(BUZZER_PORT, BUZZER_PIN, GPIO_PIN_RESET); } } } static void MX_GPIO_Init(void) { GPIO_InitTypeDef GPIO_InitStruct = {0}; // 使能GPIO时钟 __HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); __HAL_RCC_GPIOC_CLK_ENABLE(); // 配置流水灯引脚为输出模式 GPIO_InitStruct.Pin = LED_PIN1 | LED_PIN2 | LED_PIN3 | LED_PIN4 | LED_PIN5 | LED_PIN6 | LED_PIN7 | LED_PIN8; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(LED_PORT, &GPIO_InitStruct); // 配置蜂鸣器引脚为输出模式 GPIO_InitStruct.Pin = BUZZER_PIN; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(BUZZER_PORT, &GPIO_InitStruct); // 配置按键引脚为输入模式,上拉电阻使能 GPIO_InitStruct.Pin = BUTTON_PIN; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(BUTTON_PORT, &GPIO_InitStruct); } void SystemClock_Config(void) { // 系统时钟配置(根据开发板实际情况进行配置) // 这里使用默认的系统时钟配置 } |