标签:
就是按键矩阵代码书写的一个说明,就是讲K5到K7先输出高电平,而K1和K4则调成上拉输入,如果检测到K1到K4有一个变为0,说明有按键按下去,立刻进行转换,是的K1到K4设置为输出高电平,然后读取K5到K7为上拉输入,然后再读取到为0的点,通过这两个数据就能确定按下了那个按键。
1、头文件
#ifndef __KEYSQUARE_H #define __KEYSQUARE_H /***********宏定义************/ #define keySquare_K1 PTD7 #define keySquare_K2 PTD6 #define keySquare_K3 PTD5 #define keySquare_K4 PTD4 #define keySquare_K5 PTD3 #define keySquare_K6 PTD2 #define keySquare_K7 PTD1 #define Keynum1 1 #define Keynum2 2 #define Keynum3 3 #define Keynum4 4 #define Keynum5 5 #define Keynum6 6 #define Keynum7 7 #define Keynum8 8 #define Keynum9 9 #define Keynum10 10 #define Keynum11 11 #define Keynum12 12 /*****************************/ /***********函数神经***********/ int keyBoard_get(void); /*****************************/ #endif
2、源文件
#include "include.h" #include "common.h" #include "OLED.h" #include "gpio.h" #include "KeySquare.h" #include "lptmr.h" int keyBoard_get(void) { unsigned char tempdata=0x00; unsigned char bdata=0x00; int keyNum=0; //设置为输入,用于检测 gpio_init (keySquare_K1, GPI , 1); gpio_init (keySquare_K2, GPI , 1); gpio_init (keySquare_K3, GPI , 1); gpio_init (keySquare_K4, GPI , 1); //设置为上拉 port_init_NoALT(keySquare_K1,PULLUP ); port_init_NoALT(keySquare_K2,PULLUP ); port_init_NoALT(keySquare_K3,PULLUP ); port_init_NoALT(keySquare_K4,PULLUP ); //设置为输出 gpio_init (keySquare_K5,GPO , 0); gpio_init (keySquare_K6,GPO , 0); gpio_init (keySquare_K7,GPO , 0); lptmr_delay_us(4); tempdata = gpio_get(keySquare_K1); tempdata += gpio_get(keySquare_K2) << 1; tempdata += gpio_get(keySquare_K3) << 2; tempdata += gpio_get(keySquare_K4) << 3; if(tempdata != 0xff) { bdata = (tempdata << 4) | 0x00; gpio_init (keySquare_K1, GPO , 0); gpio_init (keySquare_K2, GPO , 0); gpio_init (keySquare_K3, GPO , 0); gpio_init (keySquare_K4, GPO , 0); gpio_init (keySquare_K5,GPI , 1); gpio_init (keySquare_K6,GPI , 1); gpio_init (keySquare_K7,GPI , 1); //上拉 port_init_NoALT(keySquare_K5,PULLUP); port_init_NoALT(keySquare_K6,PULLUP); port_init_NoALT(keySquare_K7,PULLUP); lptmr_delay_us(4); tempdata = gpio_get(keySquare_K5); tempdata += gpio_get(keySquare_K6) << 1; tempdata += gpio_get(keySquare_K7) << 2; bdata += tempdata; switch(bdata) { case 230: keyNum=Keynum1; break; case 214: keyNum=Keynum2; break; case 182: keyNum=Keynum3; break; case 118: keyNum=Keynum4; break; case 229: keyNum=Keynum5; break; case 213: keyNum=Keynum6; break; case 181: keyNum=Keynum7; break; case 117: keyNum=Keynum8; break; case 227: keyNum=Keynum9; break; case 211: keyNum=Keynum10; break; case 179: keyNum=Keynum11; break; case 115: keyNum=Keynum12; break; default: break; } } return keyNum; }
使用的时候,在Main函数进行调用,每次会返回一个值,0表示没有按下去,否则就返回对应的按键值。
标签:
原文地址:http://www.cnblogs.com/BlueMountain-HaggenDazs/p/4912233.html