實驗原理:
按鍵的一端與STM32 PB9相連,另外一端接地,且PB9外接一個1K電阻大小的上拉電阻,
初始化時把PB9設定成輸入模式,當按鍵彈起時,PB9由於上拉電阻的作用呈高電平(3.3V);
當按鍵按下時,PB9直接被按鍵短接到GND,呈低電平,因此判斷PB9的電平變化可得到按鍵狀態。
實驗現象:
該按鍵每按下一次,LED改變一次狀態。
原始碼下載連結:
連結:http://pan.baidu.com/s/1mhPhFfy 密碼:rrgr
核心原始碼:
int main(void) { /* USER CODE BEGIN 1 */ static int led_work_status = 0;//三色LED工作狀態 static int key_status = KEY_UP;//按鍵鬆開狀態 /* USER CODE END 1 */ /* MCU Configuration----------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); /* USER CODE BEGIN 2 */ LED_RED_ON; //初始化LED狀態 /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ //按鍵每按下一次切換一次LED狀態 while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ if(ARM_KEY_STATE == KEY_UP)key_status = KEY_UP; if(key_status == KEY_UP){ if(ARM_KEY_STATE == KEY_DOWN){ HAL_Delay(20); //按鍵消抖 if(ARM_KEY_STATE == KEY_DOWN){ key_status = KEY_DOWN; led_work_status += 1; if(led_work_status > 2)led_work_status = 0; //²Ù×÷LED switch(led_work_status){ case 0: LED_RED_ON; LED_GREEN_OFF; LED_BLUE_OFF; break; case 1: LED_RED_OFF; LED_GREEN_ON; LED_BLUE_OFF; break; case 2: LED_RED_OFF; LED_GREEN_OFF; LED_BLUE_ON; break; default: break; } } } } } /* USER CODE END 3 */ }
iCore4連結: