4X4矩形键盘
准备
我选用的芯片是STM32F407的芯片,一个4X4的矩形键盘。
我们用杜邦线将键盘和芯片连接起来,因为我选引脚为了插起来方便,我选了以下引脚。
选用了左边的引脚(4-18),这样我们刚好一排8个引脚,接上8根杜邦线。
然后根据硬件原理图,看看分别对应芯片的哪个引脚。
我们不难发现,其中的8个引脚分别是
/*
PD6 PD7 PC6 PC8
PC11 PE5 PA6 PG9
*/
当你做到这里,你离成功已经不远了。
配置引脚
这八个引脚我们要把他分成两组(上面,我已经分成上下两组,因为这有关获取键盘的数值的原理)。
下面是代码
void Keyborad_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);//GPIOD组时钟
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_6; //引脚 6
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_OUT; //输出模式
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP; //推挽输出
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz; //输出速度
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP; //上拉
GPIO_Init(GPIOD, &GPIO_InitStruct);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_7; //引脚 7
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_OUT; //输出模式
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP; //推挽输出
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz; //输出速度
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP; //上拉
GPIO_Init(GPIOD, &GPIO_InitStruct);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_6|GPIO_Pin_8; //引脚6 8
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_OUT; //输出模式
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP; //推挽输出
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz; //输出速度
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP; //上拉
GPIO_Init(GPIOC, &GPIO_InitStruct);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE); //GPIOC组时钟
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_11; //引脚11
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN; //输入模式
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP; //推挽输出
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz; //输出速度
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP; //下拉
GPIO_Init(GPIOC, &GPIO_InitStruct);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE, ENABLE); //GPIOE组时钟
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_5; //引脚5
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN; //输入模式
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP; //推挽输出
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz; //输出速度
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP; //下拉
GPIO_Init(