狀態機實現LED按鍵操作
一、按鍵狀態機
// 定義按鍵狀態 typedef enum { IDLE, // 空閑狀態 PRESS_ONCE, // 按鍵按下狀態 PRESS_LONG // 按鍵釋放狀態 } ButtonState;
二、定義LED狀態
// 定義LED狀態 typedef enum { Filck_500ms, // 500ms Filck_1s, // 1s Filck_2s, // 2s Led_On, // LED點亮 Led_OFF, // LED熄滅 LED_IDLE // LED空閑 } LED_STATE;
三、中斷處理模塊
void SysTick_Handler(void) { delay++; if (++delay_500ms > 500) { delay_500ms = 0; switch(Led_State_500ms) // LED_500ms狀態 { case Led_On: GPIO_SetBits(Port_Led_2, Pin_Led_2); // 點亮LED break; case Led_OFF: Port_Led_2->ODR ^= Pin_Led_2; // 熄滅LED break; default: break; } } }
四、主程序模塊
while (1) { if (delay > 40) { switch (Key_State) { case IDLE: if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == 0) { Key_State = PRESS_ONCE; } else { Key_State = IDLE; } break; case PRESS_ONCE: if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == 0) { Key_State = PRESS_LONG; } else { Key_State = IDLE; } break; case PRESS_LONG: if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == 0) { Key_State = PRESS_LONG; } else { Key_State = IDLE; } break; } if(Key_State == PRESS_LONG) { Led_State_500ms = Led_On; GPIO_SetBits(Port_Led_1, Pin_Led_1); } else { Led_State_500ms = Led_OFF; GPIO_ResetBits(Port_Led_1, Pin_Led_1); } } }

浙公網安備 33010602011771號