而不是执行以下操作:
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";
我建议您将错误类别(1000
s、2000
s 等)索引为矩阵的第一个索引,并将实际错误索引为数组的第二个索引:
这是想法:
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
,和. 那么除了使用一个好的旧开关/外壳外,我没有想到很酷的解决方案:1010
1042
1300
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()
函数内联,这样它就不会添加到函数调用堆栈中。
高温高压