此矩阵键盘简短易懂!
单片机源程序如下:
- #include "sys.h"
- #include "delay.h"
- #include "usart.h"
- int key_can(void);
- void GPIO_Configuration(void);
- int cheak=0;
- int main(void)
- {
- u8 ss[]={'1','2','3','A','4','5','6','B','7','8','9','C','*','0','#','D'};
- u8 t=0;
- delay_init(); //延时函数初始化
- // NVIC_Configuration(); //设置NVIC中断分组2:2位抢占优先级,2位响应优先级
- uart_init(9600); //串口初始化为9600
- GPIO_Configuration();
- printf("请按键 \n");
- while(1)
- {
- t=key_can();
- if(cheak)
- {
- printf("\n\r key=:%c \n\r",ss[t]);
- cheak=0;
- }
- }
- }
-
- /********************************************************************
- * 名称 : Keyscan()
- * 功能 : 实现按键的读取。下面这个子程序是按处理 矩阵键盘 的基本方法处理的。
- * 输入 : 无
- * 输出 : 按键值
- * 管脚 :C0-C7
- ***********************************************************************/
- /*************************************************************
- ________
- 7 | |
- 6 | |
- 5 | |
- 4 |______|
- 3 2 1 0
- *********************************************************************/
- int key_can(void)
- {
- u8 BufferH[4] = {0x7f,0xbf, 0xdf,0xef};//
- u8 j,temp;
- u8 num=16;
-
- for(j=0; j<4; j++)
- {
- GPIO_SetBits(GPIOC,GPIO_Pin_4|GPIO_Pin_5|GPIO_Pin_6|GPIO_Pin_7); //上拉输入默认高电平
- GPIO_ResetBits(GPIOC,GPIO_Pin_7>>j); //依次置0
- temp=GPIOC->IDR;
- temp=temp&BufferH[j];
- if(temp!=BufferH[j])
- {
- delay_ms(5); //可以去掉消抖
- temp=GPIOC->IDR;
- temp=temp&BufferH[j];
- if(temp!=BufferH[j])
- {
-
- if(GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_0) == 0)
- {
- num=3+j*4;
- }
- else if(GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_1) == 0)
- {
- num=2+j*4;
- }
- else if(GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_2) == 0)
- {
- num=1+j*4;
- }
- else if(GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_3) == 0 )
- {
- num=0+j*4;
- }
- }
-
-
- while(temp!=BufferH[j])
- {
- temp=GPIOC->IDR;
- temp=temp&BufferH[j];
- cheak=1;
- }
- }
- }
- return(num);
- }
-
- void GPIO_Configuration(void)
- {
- GPIO_InitTypeDef GPIO_InitStructure;
- RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOA |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_IPU; //上拉输入
- 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_Out_PP; //推挽输出
- GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
- GPIO_Init(GPIOC, &GPIO_InitStructure);
-
- }
复制代码
所有资料51hei提供下载:
矩阵键盘.rar
(301.75 KB, 下载次数: 243)
|