#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) { // 系統時鐘配置(根據開發板實際情況進行配置) // 這里使用默認的系統時鐘配置 } |