我正在 Arduino 中编写一个 USB 到 PS/2 转换器,我有一个数据结构,如果我使用另一种高级语言,我会像字典一样实现它。条目将类似于:
{ 0x29: { name: "esc", make: [0x76], break: [0xfe, 0x76] } }
此处,0x29 是 key 的 USB 代码,因此这是此字典查找的 key 。然后,我将使用 entry.name
进行调试,entry.make
是我需要在按下键 (keyDown) 和 时发送的字节数组entry.break
当键被释放时(keyUp)。
用 C++ 实现这个的方法是什么?
最佳答案
看起来像ArduinoSTL 1.1.0不包含 unordered_map
,因此您可以像这样创建一个 map
。
- 下载 Arduino STL ZIP 文件并将其放在合适的地方
- Sketch\Include Library\Add ZIP 库并为其提供 ZIP 文件的完整路径。
那么这应该可以编译,尽管有很多关于未使用变量的 STL 警告。
#include <ArduinoSTL.h>
#include <iostream>
#include <string>
#include <map>
struct key_entry {
std::string name;
std::string down;
std::string up;
key_entry() : name(), down(), up() {}
key_entry(const std::string& n, const std::string& d, const std::string& u) :
name(n),
down(d),
up(u)
{}
};
using keydict = std::map<unsigned int, key_entry>;
keydict kd = {
{0x28, {"KEY_ENTER", "\x5a", "\xf0\x5a"}},
{0x29, {"KEY_ESC", "\x76", "\xf0\x76"}}
};
void setup() {
Serial.begin( 115200 );
}
void loop() {
auto& a = kd[0x29];
// use a.down or a.up (or a.name for debugging)
Serial.write(a.up.c_str(), a.up.size());
}
关于c++ - Arduino C++ 中类似字典的数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53498564/