- /* 4*4按键矩阵,key0~15及对应value */
- uint8_t KEY_NUM[4][4] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
- uint8_t KEY_DATA[16] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0FF,0xFF};
-
- /* 按键矩阵行对应GPIO管脚 */
- #define KEY_PIN_ROW0 GPIO_PIN_4
- #define KEY_PIN_ROW1 GPIO_PIN_5
- #define KEY_PIN_ROW2 GPIO_PIN_6
- #define KEY_PIN_ROW3 GPIO_PIN_7
-
- #define KEY_GPIO_ROW0 GPIOA
- #define KEY_GPIO_ROW1 GPIOA
- #define KEY_GPIO_ROW2 GPIOA
- #define KEY_GPIO_ROW3 GPIOA
-
- /* 按键矩阵列对应GPIO管脚 */
- #define KEY_PIN_COLUMN0 GPIO_PIN_0
- #define KEY_PIN_COLUMN1 GPIO_PIN_1
- #define KEY_PIN_COLUMN2 GPIO_PIN_2
- #define KEY_PIN_COLUMN3 GPIO_PIN_3
-
- #define KEY_GPIO_COLUMN0 GPIOA
- #define KEY_GPIO_COLUMN1 GPIOA
- #define KEY_GPIO_COLUMN2 GPIOA
- #define KEY_GPIO_COLUMN3 GPIOA
-
-
- /* 扫描按键,中断模式下扫描列会反转电平,额外产生一次中断,需清中断 */
- uint8_t keyScan(uint16_t GPIO_Pin)
- {
- GPIO_TypeDef* GPIOx;
- uint8_t key_row,key_column;
-
- /* 扫描行 */
- switch(GPIO_Pin)
- {
- case KEY_PIN_ROW0:
- key_row = 0;
- GPIOx = KEY_GPIO_ROW0;
- break;
- case KEY_PIN_ROW1:
- key_row = 1;
- GPIOx = KEY_GPIO_ROW1;
- break;
- case KEY_PIN_ROW2:
- key_row = 2;
- GPIOx = KEY_GPIO_ROW2;
- break;
- case KEY_PIN_ROW3:
- key_row = 3;
- GPIOx = KEY_GPIO_ROW3;
- break;
- default:
- key_row = 3;
- break;
- }
-
- /* 扫描列-电平反转,会额外产生一次中断 */
- HAL_GPIO_WritePin(KEY_GPIO_COLUMN0,KEY_PIN_COLUMN0,GPIO_PIN_SET);
- if(HAL_GPIO_ReadPin(GPIOx,GPIO_Pin))
- {
- key_column = 0;
- }
- else
- {
- HAL_GPIO_WritePin(KEY_GPIO_COLUMN1,KEY_PIN_COLUMN1,GPIO_PIN_SET);
- if(HAL_GPIO_ReadPin(GPIOx,GPIO_Pin))
- {
- key_column = 1;
- }
- else
- {
- HAL_GPIO_WritePin(KEY_GPIO_COLUMN2,KEY_PIN_COLUMN2,GPIO_PIN_SET);
- if(HAL_GPIO_ReadPin(GPIOx,GPIO_Pin))
- {
- key_column = 2;
- }
- else
- {
- HAL_GPIO_WritePin(KEY_GPIO_COLUMN3,KEY_PIN_COLUMN3,GPIO_PIN_SET);
- if(HAL_GPIO_ReadPin(GPIOx,GPIO_Pin))
- {
- key_column = 3;
- }
- }
- }
- }
- HAL_GPIO_WritePin(KEY_GPIO_COLUMN0,GPIO_PIN_0,GPIO_PIN_RESET);
- HAL_GPIO_WritePin(KEY_GPIO_COLUMN1,GPIO_PIN_1,GPIO_PIN_RESET);
- HAL_GPIO_WritePin(KEY_GPIO_COLUMN2,GPIO_PIN_2,GPIO_PIN_RESET);
- HAL_GPIO_WritePin(KEY_GPIO_COLUMN3,GPIO_PIN_3,GPIO_PIN_RESET);
-
- printf("key%d\r\n",KEY_NUM[key_row][key_column]);
- return KEY_NUM[key_row][key_column];
- }