网上的矩阵键盘代码非常非常多,但绝大部分都是要连续I/O口的,就比如PA0-PA7、PB3-PB10等等等,这些都要用到一排的连续的单片机引脚。用过STM32单片机的都知道,STM32单片机一排过去连续的引脚的不是很多,就算刚好出现了一排PA0-PA10,可是呢,PA2、PA3串口2要用,PA9、PA10串口1要用,这就显得比较局限。而且市面上的那些很多都是修改引脚要全文上下一处处修改,麻烦且容易错漏。市面上大部分矩阵键盘扫描代码如下:
unsigned char Get_4x4_Key(void)
{
unsigned char temp_key,key;
GPIO_Write(GPIOF,0x00fe);
temp_key = GPIO_ReadInputData(GPIOF);
temp_key = temp_key&0x00f0; //0000000011110000
if(temp_key != 0x00f0)
{
Delay(10);
temp_key = GPIO_ReadInputData(GPIOF);
temp_key = temp_key&0x00f0;
if(temp_key!=0x00f0)
{
temp_key = GPIO_ReadInputData(GPIOF);
switch(temp_key)
{
case 0x00ee: key=0; break;
case 0x00de: key=1; break;
case 0x00be: key=2; break;
case 0x007e: key=3; break;
}
while(temp_key!=0x00f0) //等待按键释放
{
temp_key = GPIO_ReadInputData(GPIOF);
temp_key = temp_key&0x00f0;
}
}
}
GPIO_Write(GPIOF,0x00fd);
temp_key = GPIO_ReadInputData(GPIOF);
temp_key=temp_key&0x00f0; //11110000
if(temp_key!=0x00f0)
{
Delay(10);
temp_key = GPIO_ReadInputData(GPIOF);
temp_key=temp_key&0x00f0;
if(temp_key!=0x00f0)
{
temp_key = GPIO_ReadInputData(GPIOF);
switch(temp_key)
{
case 0x00ed: key=4; break;
case 0x00dd: key=5; break;
case 0x00bd: key=6; break;
case 0x007d: key=7; break;
}
while(temp_key!=0x00f0) //等待按键释放
{
temp_key = GPIO_ReadInputData(GPIOF);
temp_key=temp_key&0x00f0;
}
}
}
GPIO_Write(GPIOF,0x00fb);
temp_key = GPIO_ReadInputData(GPIOF);
temp_key=temp_key&0x00f0; //11110000
if(temp_key!=0x00f0)
{
Delay(10);
temp_key = GPIO_ReadInputData(GPIOF);
temp_key=temp_key&0x00f0;
if(temp_key!=0x00f0)
{
temp_key = GPIO_ReadInputData(GPIOF);
switch(temp_key)
{
case 0x00eb: key=8; break;
case 0x00db: key=9; break;
case 0x00bb: key=10; break;
case 0x007b: key=11; break;
}
while(temp_key!=0x00f0) //等待按键释放
{
temp_key = GPIO_ReadInputData(GPIOF);
temp_key=temp_key&0x00f0;
}
}
}
GPIO_Write(GPIOF,0x00f7);
temp_key = GPIO_ReadInputData(GPIOF);
temp_key=temp_key&0x00f0; //11110000
if(temp_key!=0x00f0)
{
Delay(10);
temp_key = GPIO_ReadInputData(GPIOF);
temp_key=temp_key&0x00f0;
if(temp_key!=0x00f0)
{
temp_key = GPIO_ReadInputData(GPIOF);
switch(temp_key)
{
case 0x00e7: key=12; break;
case 0x00d7: key=13; break;
case 0x00b7: key=14; break;
case 0x0077: key=15; break;
}
while(temp_key!=0x00f0) //等待按键释放
{
temp_key = GPIO_ReadInputData(GPIOF);
temp_key=temp_key&0x00f0;
}
}
}
return key;
}
由上面代码,你们设想一下,如果我们需要改一个或几个引脚,那要改多少个地方?以你的水平需要多长时间?你用来修改这些地方的时间是不是可以用来多做几道题?
所以重点来了:如果我矩阵键盘的引脚可以随便定义