1

我正在尝试根据来自外部设备的整数返回来确定从 PROGMEM 检索和显示错误消息的最佳方法。

const prog_char error_1000[] PROGMEM = "No data provided.";
const prog_char error_1001[] PROGMEM = "device not activated";
const prog_char error_2000[] PROGMEM = "Machine ID invalid";
const prog_char error_3000[] PROGMEM = "Insufficient Balance";

void loop()
{
   int result = device.GetStatus();
   Serial.println(/*error by code here*/);
}

错误按前导数字分组(即,1xxx 是设备错误,2xxx 是另一个组件的问题,3xxx 是事务错误)。不过,每个类别中可能只有 5-10 个错误。

我正在使用一些内存重的库,并且我的内存在 Uno 上已经几乎耗尽,所以我试图在这里保持小东西。

基本上以某种方式通过 ID 查找字符串是必需的,但我在最好的方法上没有取得太大进展。

4

1 回答 1

0

而不是执行以下操作:

const prog_char error_1000[] PROGMEM = "No data provided.";
const prog_char error_1001[] PROGMEM = "device not activated";
const prog_char error_2000[] PROGMEM = "Machine ID invalid";
const prog_char error_3000[] PROGMEM = "Insufficient Balance";

我建议您将错误类别(1000s、2000s 等)索引为矩阵的第一个索引,并将实际错误索引为数组的第二个索引:

这是想法:

const prog_char error_code[1][0] PROGMEM = "No data provided.";
const prog_char error_code[1][1] PROGMEM = "device not activated";
const prog_char error_code[2][0] PROGMEM = "Machine ID invalid";
const prog_char error_code[3][0] PROGMEM = "Insufficient Balance";

(编辑)这是一个有效的语法:

const prog_char* error_code[][3] PROGMEM = {{"ERROR 1000", "ERROR 1001", "ERROR 1002"},
                                            {"ERROR 2000", "ERROR 2001", "ERROR 2002"},
                                            {"ERROR 3000", "ERROR 3001", "ERROR 3002"}};

唯一的缺点是您必须指定内部数组的长度,因此需要在每个内部数组中具有相同数量的字符串。

然后你可以编写一个进行状态码转换的函数:

const prog_char* fmt_error(int code) {
    return error_code[code/1000][code%1000];
}

void loop()
{
   int result = device.GetStatus();
   Serial.println(fmt_error(result));
}

该解决方案不使用比使用一个数组更多的内存(仅多一个指针)。唯一的缺点是如果您需要不连续的状态代码,例如1000,和. 那么除了使用一个好的旧开关/外壳外,我没有想到很酷的解决方案:101010421300

const prog_char* fmt_error(int code) {
    switch (code) {
        case (1000): return F("Error XXX");
        case (1042): return F("Error which code is not contiguous");
        case (2042): return F("Another error");
    }
}

(编辑)我对如何处理您的问题有第三个想法:

typedef struct
{
    int code;
    prog_char* message;
} error_code;

const error_type error_codes[] =
{
    {0000, F("Unknown error code")},
    {1000, F("Error foo")},
    {1001, F("Error bar")},
    {2000, F("Error foobar")}
    ...
};

const prog_char* fmt_error(int code) {
    for (int i=0; i<sizeof(error_codes);++i)
        if (error_codes[i].code == code)
            return error_codes[i].message;
    return error_codes[0];
}

但我认为在所有三个解决方案中使用较少内存的解决方案是第二个使用用例的解决方案。因为一切都在程序存储器中完成,并且由于F()宏,所有字符串都在闪存中。为了节省一些额外的字节,您甚至可以使fmt_error()函数内联,这样它就不会添加到函数调用堆栈中。

高温高压

于 2013-06-30T21:02:32.780 回答