此矩陣鍵盤簡短易懂!
單片機源程序如下:
- #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)
2018-4-3 03:20 上傳
點擊文件名下載附件
矩陣鍵盤 下載積分: 黑幣 -5
|