-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathkeypad.c
More file actions
138 lines (109 loc) · 2.51 KB
/
keypad.c
File metadata and controls
138 lines (109 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/* keypad.c
*
* Keypad driver
* Provides a single function:
* int keyPress();
* Returns -1 if no key pressed
* and 0x00..0x0F to identify
* a key thas is pressed
*
* Original - WDH September 2006
* Updated (improved documentation) - WDH September 2008
*
*/
#include "config.h"
#include "keypad.h"
#include "Delay.h"
#include "AT91PIO.h"
#include "Sound.h"
int keyCode[4][4] =
{
{1,2,3,0x0f},
{4,5,6,0x0e},
{7,8,9,0x0d},
{0x0a,0x00,0x0b,0x0c}
};
static void PullRowsLow( void ){
OutputLow( Y1 );
OutputLow( Y2 );
OutputLow( Y3 ); /* In error */
OutputLow( Y4 );
}
/*
* Check each column - the column line with a keypress should be low
*/
static int calculateColumn( unsigned long port ) {
if ( !(port & X1) )
return 1;
else if ( !(port & X2) )
return 2;
else if ( !(port & X3) )
return 3;
else
return 4;
}
int calculateRow( unsigned long column ) {
OutputLow(Y1);
OutputHigh(Y2);
OutputHigh(Y3);
OutputHigh(Y4);
if ( column & ~__PIO_PDSR )
return 1;
OutputHigh(Y1);
OutputLow(Y2);
if ( column & ~__PIO_PDSR )
return 2;
OutputHigh(Y2);
OutputLow(Y3);
if ( column & ~__PIO_PDSR )
return 3;
OutputHigh(Y3);
OutputLow(Y4);
if ( column & ~__PIO_PDSR )
return 4;
return 5;
}
/* keyPress()
* Returns -1 if no key pressed
* and 0x00..0x0F to identify
* a key thas is pressed
*
* Columns - X1..X4 configured for Input;
* Rows - Y1..Y4 configured for Output;
* Pull rows low;
* Read columns;
* If (no column low)
* return -1;
* Assign column value;
*/
int keyPress(){
unsigned long port; // IOPort value
int column;
int row;
PullRowsLow();
/* Read IO port */
port = __PIO_PDSR;
/* Return -1 if no key pressed */
if ( ( port & X1 ) && ( port & X2 ) && ( port & X3 ) && ( port & X4 ) )
return -1;
/* Calculate column position */
column= calculateColumn( port );
/* Delay for key bounce interval */
Delay_ms( 20 );
/* Read port again */
port = __PIO_PDSR; /* Pin Data Status Register */
/* Test for key bounce */
if ( column != calculateColumn( port ) )
return -1;
if ( !(port & X1) )
row= calculateRow( X1 );
else if ( !(port & X2) )
row= calculateRow( X2 );
else if ( !(port & X3) )
row= calculateRow( X3 );
else if ( !(port & X4) )
row= calculateRow( X4 );
else
return -1;
return keyCode[row-1][column-1];
}