Mon, 26 Oct 2020 00:16:13 +0100
Extracted the display related functions in a Display class
33 | 1 | #include "mbed.h" |
2 | #include "Keypad.h" | |
3 | ||
4 | ||
5 | Keypad::Keypad( | |
6 | uint8_t nRows, | |
7 | DigitalIn rows[], | |
8 | uint8_t nColumns, | |
9 | DigitalOut cols[], | |
10 | int debounce_ms): | |
11 | _rows(), | |
12 | _columns(), | |
13 | _debounce(debounce_ms), | |
14 | _started(false), | |
15 | _nrows(nRows), | |
16 | _ncols(nColumns) | |
17 | { | |
18 | printf("Setup Keypad: %dx%d\r\n", nColumns, nRows); | |
19 | for(uint8_t c=0; c<nColumns; c++) | |
20 | { | |
21 | _columns.push_back(cols[c]); | |
22 | _columns[c].write(0); | |
23 | } | |
24 | ||
25 | for(uint8_t r=0; r<nRows; r++) | |
26 | { | |
27 | _rows.push_back(rows[r]); | |
28 | _rows[r].mode(PullDown); | |
29 | } | |
30 | _keys = new uint8_t[_nrows*_ncols]; | |
31 | } | |
32 | ||
33 | Keypad::~Keypad() | |
34 | { | |
35 | delete _keys; | |
36 | } | |
37 | ||
38 | void Keypad::run() | |
39 | { | |
40 | uint8_t col=0; | |
41 | uint8_t row; | |
42 | ||
43 | for (row=0; row<(_ncols*_nrows); row++) | |
44 | _keys[row] = 0; | |
45 | ||
46 | while(_started) | |
47 | { | |
48 | // activate column col | |
49 | _columns[col].write(1); | |
50 | ThisThread::sleep_for(5); | |
51 | for(row=0; row<_nrows; row++) | |
52 | { | |
53 | if (_rows[row].read()) | |
54 | { | |
55 | if (_keys[row + _nrows*col] < 2) // ensure only one key is pressed in this column | |
56 | { | |
57 | _keys[row + _nrows*col]++; | |
58 | if ((_keys[row + _nrows*col] == 2) && _kp_callback) | |
59 | _kp_callback.call(row, col); | |
60 | } | |
61 | } | |
62 | else | |
63 | { | |
64 | if (_keys[row + _nrows*col] > 0) | |
65 | { | |
66 | _keys[row + _nrows*col]--; | |
67 | if ((_keys[row + _nrows*col] == 0) && _kr_callback) | |
68 | _kr_callback.call(row, col); | |
69 | } | |
70 | } | |
71 | } | |
72 | _columns[col].write(0); | |
73 | col = (col+1) % _ncols; | |
74 | ThisThread::sleep_for(5); | |
75 | } | |
76 | } | |
77 | ||
78 | void Keypad::attach(const keyevent_callback_t& kp_callback, | |
79 | const keyevent_callback_t& kr_callback) | |
80 | { | |
81 | _kp_callback = kp_callback; | |
82 | _kr_callback = kr_callback; | |
83 | } | |
84 | ||
85 | void Keypad::start(void) | |
86 | { | |
87 | if (_started) | |
88 | return; | |
89 | _started = true; | |
90 | _loop.start(callback(this, &Keypad::run)); | |
91 | } | |
92 | ||
93 | void Keypad::stop(void) | |
94 | { | |
95 | _started = false; | |
96 | } |