Stm32 矩阵键盘扫描程序分析
我们知道在51单片机中,通过扫描某个口的电平高低得知那个按键按下,比如,控制两行4列,
假如让P1=0xCf;低位都置1 (pb0-pb3),pb4-pb5置0;然后我们就扫描P1口就行了,如果有按键被按下的,高电平会被强制拉低的。
假如按键返回的值为0xce,可知是pb0被拉低了,由此可判断是S1或者S2按下了,其他的同理。
当然只让P1=0xcf,是不能判断出具体的按键是哪个的,此时,如果我们取反既P1=0x30;
当按键返回值为0x10时,我们可得知01 0000,pb5=0,s1或者s2被按下,这个时候我们将0xce|0x10=0xde,就是唯一的值了。以此类推,得出其他的值来。
在stm32中是同样的大道理;
uint8_t KeyScan(void) { uint8_t HangValue = 0; uint8_t LieValue = 0; uint16_t KeyValue = 0; uint8_t Tmp =0; static uint8_t KeyConter = 0; GPIO_SetBits(Colum1.port, (Colum1.pin|Colum2.pin|Colum3.pin|Colum4.pin)); GPIO_ResetBits(Line1.port,(Line1.pin|Line2.pin)); Tmp = GPIO_ReadInputData(Line1.port); if ((Tmp&0x0F) != 0x0F) { if (KeyConter < 1) {//去抖 KeyConter++; } else { HangValue = Tmp&0x0f; GPIO_ResetBits(Colum1.port, (Colum1.pin|Colum2.pin|Colum3.pin|Colum4.pin)); GPIO_SetBits(Line1.port,(Line1.pin|Line2.pin)); Tmp = GPIO_ReadInputData(Colum1.port); LieValue = Tmp&0x30; KeyValue = (HangValue)|LieValue; if (KeyValue)// KeyValue^KeyValueBkp { KeyValueBkp = KeyValue; switch (KeyValue) { // case KEY_10: return KEY_NUM_0;//16;----0 case KEY_01: return KEY_NUM_1;//3;-----1 case KEY_02: return KEY_NUM_2;//4;-----2 case KEY_03: return KEY_NUM_3;//5;-----3 case KEY_04: return KEY_NUM_4;//7;-----4 case KEY_05: return KEY_NUM_5;//8;-----5 case KEY_06: return KEY_NUM_6;//9;-----6 case KEY_07: return KEY_NUM_7;//11----7 case KEY_08: return KEY_NUM_8;//------8 default: return 0; } } else { return 0; } } } else { KeyConter = 0; //计数清零 KeyValueBkp = 0; } return 0; } typedef struct { GPIO_TypeDef *port; uint16_t pin; }Matrix_t; //const Matrix_t Colum1 = {GPIOD, GPIO_PIN_2}; //const Matrix_t Colum2 = {GPIOD, GPIO_PIN_3}; //const Matrix_t Colum3 = {GPIOD, GPIO_PIN_4}; const Matrix_t Colum1 = {GPIOB, GPIO_Pin_0}; const Matrix_t Colum2 = {GPIOB, GPIO_Pin_1}; const Matrix_t Colum3 = {GPIOB, GPIO_Pin_2}; const Matrix_t Colum4 = {GPIOB, GPIO_Pin_3}; const Matrix_t Line1 = {GPIOB, GPIO_Pin_4}; const Matrix_t Line2 = {GPIOB, GPIO_Pin_5}; #define KEY_01 0x1e #define KEY_02 0x2e #define KEY_03 0x1d #define KEY_04 0x2d #define KEY_05 0x1b #define KEY_06 0x2b #define KEY_07 0x17 #define KEY_08 0x27