Emakefun Matrix Keyboard Arduino 库 1.0.1
载入中...
搜索中...
未找到
matrix_keyboard.cpp
1#include "matrix_keyboard.h"
2
3namespace emakefun {
4
5MatrixKeyboard::MatrixKeyboard(TwoWire& wire, const uint8_t i2c_address) : wire_(wire), i2c_address_(i2c_address), key_(kKeyNone) {
6}
7
10 for (uint8_t i = 0; i < 5; i++) {
11 wire_.beginTransmission(i2c_address_);
12 result = static_cast<ErrorCode>(wire_.endTransmission());
13 if (result == ErrorCode::kOK) {
14 return result;
15 }
16 }
17 return result;
18}
19
21 last_key_ = key_();
22 key_ = ReadKey();
23}
24
26 return (last_key_ & key) == 0 && (key_() & key) != 0;
27}
28
30 return (last_key_ & key) != 0 && (key_() & key) != 0;
31}
32
34 return (last_key_ & key) != 0 && (key_() & key) == 0;
35}
36
38 return (last_key_ & key) == 0 && (key_() & key) == 0;
39}
40
42 if (Pressed(key)) {
44 } else if (Pressing(key)) {
46 } else if (Released(key)) {
48 }
49
51}
52
54 static constexpr struct {
55 Key key;
56 char value;
57 } key_value_map[] = {{kKey1, '1'},
58 {kKey2, '2'},
59 {kKey3, '3'},
60 {kKey4, '4'},
61 {kKey5, '5'},
62 {kKey6, '6'},
63 {kKey7, '7'},
64 {kKey8, '8'},
65 {kKey9, '9'},
66 {kKey0, '0'},
67 {kKeyA, 'A'},
68 {kKeyB, 'B'},
69 {kKeyC, 'C'},
70 {kKeyD, 'D'},
71 {kKeyAsterisk, '*'},
72 {kKeyNumberSign, '#'}};
73
74 for (const auto& key_map : key_value_map) {
75 if ((last_key_ & key_map.key) == 0 && (key_() & key_map.key) != 0) {
76 return key_map.value;
77 }
78 }
79
80 return '\0';
81}
82
83MatrixKeyboard::Key MatrixKeyboard::ReadKey() {
84 Key key = kKeyNone;
85
86 if (sizeof(key) != wire_.requestFrom(i2c_address_, sizeof(key))) {
87 return key;
88 }
89
90 if (sizeof(key) != wire_.readBytes(reinterpret_cast<uint8_t*>(&key), sizeof(key))) {
91 return key;
92 }
93
94 return key;
95}
96} // namespace emakefun
char GetCurrentPressedKey() const
获取当前按下的按键。
bool Idle(const Key key) const
查询按键是否空闲。
MatrixKeyboard(TwoWire &wire, const uint8_t i2c_address)
构造函数
bool Pressing(const Key key) const
查询按键是否被按住。
bool Pressed(const Key key) const
查询按键是否被按下。
ErrorCode Initialize()
初始化。
KeyState GetKeyState(const Key key) const
查询按键状态。
bool Released(const Key key) const
查询按键是否被释放。
void Tick()
扫描按键,在函数loop中调用,每次循环先调用该函数再查询按键状态。