【发布时间】:2025-12-03 13:35:01
【问题描述】:
在我的程序中,我有一个用于索引数组成员的枚举。原因是我更容易理解我正在访问的参数而不知道它在数组中的索引
enum param_enum
{
AA,
AB,
AC,
AD,
PARAM_COUNT
};
static int16_t parameters[PARAM_COUNT] =
{
[AA] = 5,
[AB] = 3,
[AC] = 4,
[AD] = 8,
};
然后我可以访问任何参数,例如:
parameters[AA] = 10; // Update AA parameter to value 10.
我将收到串行命令,例如:
"AA:15"
当我收到这个命令时,我必须根据前2个字符确定我需要修改什么参数,然后跳过第3个字符(因为它只是“:”,我不关心它)剩下的字符会显示新值)
我想知道是否有更简单的方法将枚举映射到字符串
我目前的方法:
// line holds the string data
// cmd_size is the length of string data
bool parse_command(char *line, uint16_t cmd_size)
{
printf("data size = %u \n",cmd_size);
char temp_buf[3] = {0};
temp_buf[0] = line[0];
temp_buf[1] = line[1];
printf("temp_buf = %s \n",temp_buf);
if (!strcmp("aa", temp_buf))
{
printf("aa: detected \n");
char temp_storage[5];
int16_t final_value;
for(int i = 3;i<=cmd_size; i++){
temp_storage[i-3]=line[i]; // read data and append to temp bufferfrom the 3rd character till the end of line
if(line[i] == 0){
printf("null termination triggered \n");
final_value = strtol(temp_storage,NULL,10); // convert char array to int16_t
printf("temp var = %i \n",final_value);
}
}
return true;
}
}
上述方法似乎工作正常,但我认为这不是这个特定任务最合适的解决方案。
【问题讨论】:
-
(char*)param->write.value是在:之后终止还是在它之后也有值?:之前的字符数是总是2还是变长? -
“更容易”到底是什么意思?
-
蓝牙命令字符串的末尾有一个空终止符。
:之后的数据并不总是长度为2 -
对不起,我遗漏了一些重要信息。我已经更新了我最初的问题
标签: c string enums esp32 strcmp