3

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++?

kolrie
  • 12,562
  • 14
  • 64
  • 98

1 Answers1

3

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());
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • I am getting multiple compiling errors: https://gist.github.com/fcoury/cab3fbc3a8fdc40f109475e5320b36de – kolrie Nov 27 '18 at 17:11
  • I have the sketch here if you want: https://create.arduino.cc/editor/fcoury/483d1d94-afd1-4b31-85d2-7658cc2daf12/preview – kolrie Nov 27 '18 at 17:20
  • I'll see if I can get my arduino-environment up. Haven't started it in years and have never used the STL in it myself. Will be interesting :-) – Ted Lyngmo Nov 27 '18 at 17:23
  • That is really appreciated. i am updating the Gist with new attempts I'm making. Thanks! – kolrie Nov 27 '18 at 17:36
  • I think I got it! Check this new gist:https://gist.github.com/fcoury/623d3d0ce9be0dddba80779172b9e51e – kolrie Nov 27 '18 at 17:44
  • Looking good! I changed my answer to use `std::string` and also added how I think you should be able to do `Serial.write(buf, len);`. – Ted Lyngmo Nov 27 '18 at 18:01
  • 1
    That's great! I just realized that the initialization I proposed is a bit clumsy so I just edited it to show a simpler way (although I don't know if the numbers I put in there are correct or not). – Ted Lyngmo Nov 28 '18 at 20:11
  • Looks great and yes, this looks cleaner as well. Thanks! – kolrie Nov 29 '18 at 00:02