|
本帖最后由 cady 于 2014-3-28 09:23 编辑
键盘是人机对话不可缺少的组件之一,在按键比较少时,我们可以一个pcDuino的I/O口接一个按键,但当按键需要很多,而pcDuino的I/O资源又比较紧张时,使用矩阵式键盘无疑是最好的选择。下面来介绍如何在pcDuino上使用4×4矩阵键盘。
一、硬件清单:
- pcDuino V2 x1
- 4×4 keyboard x1
- Wire x8
- 二、接线说明
-
- 三、测试代码:
#include "core.h"
int rowpins[4] = {2,3,4,5};
int colpins[4] = {6,7,8,9};
int key_value=0x00;
int row_value=0,col_value=0;
void clean_pins(int p[])
{
for(int i=0;i<4;i++)
{
pinMode(p,OUTPUT);
digitalWrite(p,HIGH);
}
}
void SetPinMode(int p[],int mode)
{
for(int i=0;i<4;i++)
{
pinMode(p,mode);
if(mode==OUTPUT)
{
digitalWrite(p,LOW);
}
}
}
int ReadPin(int p[])
{
int value=0;
int pin=0;
for(int i=0;i<4;i++)
{
pin = digitalRead(p);
if(pin == 0)
{
delay(50);
pin = digitalRead(p);
if(pin == 0)
{
if(i==0) value = 0x01;
if(i==1) value = 0x02;
if(i==2) value = 0x04;
if(i==3) value = 0x08;
}
}
}
return value;
}
void ReadRow()
{
row_value = 0;
SetPinMode(rowpins,OUTPUT);
clean_pins(colpins);
SetPinMode(colpins,INPUT);
row_value = ReadPin(colpins);
}
void ReadCol()
{
col_value = 0;
SetPinMode(colpins,OUTPUT);
clean_pins(rowpins);
SetPinMode(rowpins,INPUT);
col_value = ReadPin(rowpins);
}
void setup()
{
printf("4x4 keypad test:\n");
}
void loop()
{
char key;
ReadRow();
if(row_value!=0)
{
delay(20);
ReadCol();
key_value = (row_value<<4) + col_value;
switch(key_value)
{
case 0x11: key = '1' ; break;
case 0x21: key = '2' ; break;
case 0x41: key = '3' ; break;
case 0x81: key = 'A' ; break;
case 0x12: key = '4' ; break;
case 0x22: key = '5' ; break;
case 0x42: key = '6' ; break;
case 0x82: key = 'B' ; break;
case 0x14: key = '7' ; break;
case 0x24: key = '8' ; break;
case 0x44: key = '9' ; break;
case 0x84: key = 'C' ; break;
case 0x18: key = '*' ; break;
case 0x28: key = '0' ; break;
case 0x48: key = '#' ; break;
case 0x88: key = 'D' ; break;
default : 0x00;
}
if(key!=0x00)
printf("key value = %c\n+++++++++\n",key);
//delay(100);
}
}
- 四、测试运行:(1)按照接线图接线:
- (2)打开Arduino IDE,输入测试代码:
- (3)编译运行代码,按下任意按键,在终端可以看到打印的键值:
|
|