kolrie
kolrie

Reputation: 12732

Dictionary like data structure in Arduino C++

I am writing a USB to PS/2 converter in Arduino and I have a data structure that I would implement like a dictionary if I were using another higher level language. The entries would be something like:

{ 0x29: { name: "esc", make: [0x76], break: [0xfe, 0x76] } }

Here, 0x29 is the USB code for the key, so that's the key for this dictionary lookup. Then, I would use entry.name for debugging purposes, entry.make is the array of bytes I need to send when the key is pressed (keyDown) and entry.break when the key is released (keyUp).

What would be a a way to achieve this in C++?

Upvotes: 3

Views: 3253

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

It looks like ArduinoSTL 1.1.0 doesn't include unordered_map so you could create a map like this.

  1. Download the Arduino STL ZIP file and put it somewhere good
  2. Sketch\Include Library\Add ZIP library and give it the full path to the ZIP file.

Then this should compile, albeit with a lot of STL warnings about unused variables.

#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());
}

Upvotes: 3

Related Questions