stm32f103 5*4矩阵键盘代码
时间: 2023-11-08 10:04:21 浏览: 67
以下是一个基于STM32F103芯片的5*4矩阵键盘代码:
```c
#include "stm32f10x.h"
#define KEY_PORT GPIOA
#define ROW1_PIN GPIO_Pin_0
#define ROW2_PIN GPIO_Pin_1
#define ROW3_PIN GPIO_Pin_2
#define ROW4_PIN GPIO_Pin_3
#define COL1_PIN GPIO_Pin_4
#define COL2_PIN GPIO_Pin_5
#define COL3_PIN GPIO_Pin_6
#define COL4_PIN GPIO_Pin_7
#define COL_NUM 4
#define ROW_NUM 4
void key_init(void);
uint8_t key_scan(void);
int main(void)
{
key_init();
while (1)
{
uint8_t key_value = key_scan();
if (key_value != 0)
{
// 处理按键按下事件
}
}
}
void key_init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = ROW1_PIN | ROW2_PIN | ROW3_PIN | ROW4_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(KEY_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = COL1_PIN | COL2_PIN | COL3_PIN | COL4_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(KEY_PORT, &GPIO_InitStructure);
}
uint8_t key_scan(void)
{
uint8_t row, col, key_value;
for (col = 0; col < COL_NUM; col++)
{
GPIO_SetBits(KEY_PORT, COL1_PIN << col);
for (row = 0; row < ROW_NUM; row++)
{
if (GPIO_ReadInputDataBit(KEY_PORT, ROW1_PIN << row) == 0)
{
key_value = (row * COL_NUM + col + 1);
while (GPIO_ReadInputDataBit(KEY_PORT, ROW1_PIN << row) == 0)
;
GPIO_ResetBits(KEY_PORT, COL1_PIN << col);
return key_value;
}
}
GPIO_ResetBits(KEY_PORT, COL1_PIN << col);
}
return 0;
}
```
这里使用了GPIOA口作为键盘的输入输出口,将行线(PA0~PA3)设置为上拉输入,列线(PA4~PA7)设置为推挽输出。在按键扫描时,将每一列线依次拉低,并检查每一行线上的电平状态,如果发现有电平变低,说明对应的按键被按下,返回该按键的键值。
阅读全文