-
Notifications
You must be signed in to change notification settings - Fork 0
/
keypad.js
119 lines (94 loc) · 3.14 KB
/
keypad.js
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
/**
* Copyright (c) 2024
* @Version : 1.0.0
* @Repository : https://github.com/salarizadi/moddable-sdk/tree/main/Modules/keypad
* @Author : https://salarizadi.github.io
*/
import Timer from "timer"
const Digital = device.io.Digital
export default class {
#config = {
map : [],
rows : [],
columns: []
};
#callback
#pins = {}
#previous = null
#count = 0
constructor (config, callback) {
if (typeof config !== "object")
return false
this.#config = {
...this.#config,
...config
}
this.#callback = typeof callback === "function" ? callback : () => {}
this.#turnOnRows()
}
#pin (config) {
let $this = this, which = null
which = $this.#config.rows.includes(config.pin) ? "rows" : which
which = $this.#config.columns.includes(config.pin) ? "cols" : which
if (typeof $this.#pins[config.pin] !== "undefined")
$this.#pins[config.pin].close()
return $this.#pins[config.pin] = new Digital({
edge: Digital.Rising | Digital.Falling,
...config,
onReadable: function () {
if (which === "cols") return false
$this.#pressed(config, $this.#pins[config.pin], which, "click")
}
})
}
#turnOnRows ( ) {
this.#config.rows.map(pin => this.#pin({
pin : pin,
mode: Digital.InputPullUp,
edge: Digital.Falling
}))
this.#config.columns.map(pin => this.#pin({
pin : pin,
mode: Digital.InputPullDown
}))
}
#turnOnCols ( ) {
this.#config.columns.map(pin => this.#pin({
pin : pin,
mode: Digital.InputPullUp
}))
this.#config.rows.map(pin => this.#pin({
pin : pin,
mode: Digital.InputPullDown,
edge: Digital.Falling
}))
}
#pressed (config) {
try {
this.#turnOnCols()
let column = false
this.#config.columns.map(pin => {
if (!this.#pins[pin].read()) {
column = this.#config.columns.indexOf(pin)
return
}
})
if (column || column === 0) {
const indexRow = this.#config.rows.indexOf(config.pin)
if (typeof this.#config.map[indexRow] !== "undefined") {
const key = this.#config.map[indexRow][column]
if (this.#count === 0 && this.#previous !== key) {
this.#callback(key)
Timer.set(() => {
this.#previous = null
this.#count = 0
}, 150)
}
this.#previous = key
this.#count = 1
}
}
this.#turnOnRows()
} catch (e) { trace(`\nError keypad pressed : ${e}`) }
}
}