arraysarduinoindexed

Using an integer indexed list of strings with Arduino


I do have a list of string status messages. Each status message has an individual integer status code assinged to it, like this:

{0, "INITIAL STATE"},
{12, "ERROR INVERTER COMMUNICATION"},
{42, "INITIAL CHARGE"},
{158, "MAINTENANCE CHARGE"},
...

In fact the list has about 200 entries, with 256 being the maximum status code. Now I want to reference the respective string for a statuscode (int) I´m reading from the device. I have been looking at using a struct like this:

typedef struct {
    int Statuscode;
    String StatusString;
} StatusCodes;

and a definition like this:

StatusCodes MyStatuscodes[] = {
    {0, "INITIAL STATE"},
    {12, "ERROR INVERTER COMMUNICATION"},
    {42, "INITIAL CHARGE"},
    {158, "MAINTENANCE CHARGE"},
};

My questions:

I think there must be an easy solution for this, but being new to C++ I´m struggling with finding a good solution, besides maybe converting to JSON and parsing this.


Solution

  • list has about 200 entries
    256 being the max. code.

    Is there a better way than using a struct?

    Consider an array of const char *.

    Consider in some error.cpp file

    #incldue "error.h"
    const char *StatusString[STATUSSTRING_N] = {
      "INITIAL STATE",
      "UNUSED 1",  
      ...
      "UNUSED 11",  
      "ERROR INVERTER COMMUNICATION"
      ...
    };
    

    and in some error.h file

    #define STATUSSTRING_N 257
    extern const char *StatusString[STATUSSTRING_N];
    

    When I get a statuscode of e.g. 12, how do I get to the respective string?

    if (statuscode >= 0 && statuscode < STATUSSTRING_N) {
      return StatusString[statuscode];
    }