STM32 4x4矩阵键盘初始化及实现多位输入

目的:实现矩阵键盘的多位数据输入

这里以两位数据为例

//引脚初始化PC0-PC7

void Key_Config() { GPIO_InitTypeDef GPIO_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0| GPIO_Pin_1| GPIO_Pin_2 | GPIO_Pin_3; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOC, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4 | GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOC, &GPIO_InitStructure); }

//按键扫描函数

int KeyScan(void) { u8 KeyVal; GPIO_Write(GPIOC, (GPIOC->ODR & 0xfff0 | 0x000f)); if((GPIOC->IDR & 0x00f0)==0x0000) return -1; else { if((GPIOC->IDR & 0x00f0)==0x0000) return -1; } GPIO_Write(GPIOC,(GPIOC->ODR & 0xfff0 | 0x0001)); switch(GPIOC->IDR & 0x00f0) { case 0x0010: KeyVal=1; break; case 0x0020: KeyVal=2;break; case 0x0040: KeyVal=3;break; case 0x0080: KeyVal=10;break; } while((GPIOC->IDR & 0x00f0) > 0); GPIO_Write(GPIOC,(GPIOC->ODR & 0xfff0 | 0x0002)); switch(GPIOC->IDR & 0x00f0) { case 0x0010: KeyVal=4;break; case 0x0020: KeyVal=5;break; case 0x0040: KeyVal=6;break; case 0x0080: KeyVal=11;break; } while((GPIOC->IDR & 0x00f0) > 0); GPIO_Write(GPIOC,(GPIOC->ODR & 0xfff0 | 0x0004)); switch(GPIOC->IDR & 0x00f0) { case 0x0010: KeyVal=7;break; case 0x0020: KeyVal=8;break; case 0x0040: KeyVal=9;break; case 0x0080: KeyVal=12;break; } while((GPIOC->IDR & 0x00f0) > 0); GPIO_Write(GPIOC,(GPIOC->ODR & 0xfff0 | 0x0008)); switch(GPIOC->IDR & 0x00f0) { case 0x0010: KeyVal=13;break; case 0x0020: KeyVal=0;break; case 0x0040: KeyVal=15;break; case 0x0080: KeyVal=16;break; } while((GPIOC->IDR & 0x00f0) > 0); return KeyVal; }

//轮询检测是否有按键按下,有则返回键值 u8 key_input(void) { while(1) { if( GPIOC->IDR!= 0xff0f) { return KeyScan(); } } }

//幂函数运算

static u16 MYS(int a) { int aa=1; for(;a>0;a--) { aa=aa*10; } return aa; }

//循环输入数据,实现数据结合并返回 u16 key_Input() { int key[2]; u16 dd=0; int bb=1,j,i;

for(i=0;i<2;i++) { key[i]=key_input(); while(key[i]==KeyScan()){;} }

for(j=0;j<2;j++) { dd=dd+key[j]*MYS(bb); bb--; } return dd;

}

经验分享 程序员 微信小程序 职场和发展