我正在用arduino接口一些旧的定位设备,但是我用高级语言完成了我的大部分工作,我很难适应AVR-GCC的局限性。
我基本上有两个问题:这是解析字符串的好方法吗?我能做些什么来优化嵌入式平台的代码呢?
// this is in the global scope of my program. normally accepted as bad code,
// but it seems to make sense in the context of an embedded platform.
// "global" cache
int data[10];
void getPosition(){
// position message is always less than 25 bytes with null termination characters
byte bufferIndex = 0;
char buffer[25];
// read the position command from the serial port
// should look like:
// D20BIX+00733Y+00080S99\r\n
//
// and we need the X+00000 and Y+00000 parts
//
if (Serial.available() > 0){
while (Serial.available() > 0 && bufferIndex < 25){
buffer[bufferIndex] = Serial.read();
if (buffer[bufferIndex++] == '\n'){
buffer[bufferIndex] = '\0';
break;
}
}
Serial.flush();
// check to see if we have good orientation on the buffer by
// checking for lines starting with model identifier 'D'
String input = String(buffer);
if (buffer[0] == 'D' && bufferIndex <=24){
int x_result = data[1];
int y_result = data[4];
String check;
char token_buffer[8] = {'0', '0', '0', '0', '0', '0', '0', '0' };
// scan for x, target token is X+00000
String x_token = input.substring(5, 11);
check = x_token.substring(2, 6);
check.toCharArray(token_buffer, 8);
x_result = atoi(token_buffer);
if (x_token[1] == '-'){
x_result *= -1;
}
// scan for y, target token is Y+00000
String y_token = input.substring(12, 18);
check = y_token.substring(2, 6);
check.toCharArray(token_buffer, 8);
y_result = atoi(token_buffer);
if (y_token[1] == '-'){
y_result *= -1;
}
// finalize results
data[1] = x_result;
data[4] = y_result;
}
}
}
发布于 2011-04-19 21:42:56
对于嵌入式应用程序来说,IMHO字符串解析不是一个好主意。如果您真的关心速度,最好使用一些二进制格式w/o动态长度数字等。
我建议您不能因为遗留代码/硬件而更改协议。然后,您可以尝试将解析器转换为有限的自动化。您只需创建一个表(当前状态的第一个索引,对一类读字符的第二个索引,值是要调用的新状态和函数),然后用(state, f) = transition[state][class_of[*s++]]; f();
为一些简单语法生成的文件可能会有帮助。
如果您只需要对代码进行一些小的修改,就在这里。首先,将数据读入缓冲区。那么,您所要做的就是使用Horner方案进行计算:
x_result = ((buffer[5]-'0')*10+buffer[6]-'0')*10+... ;
if (buffer[4] == '-') x_result =- x_result;
字符串构造函数、子字符串方法和其他字符串操作非常昂贵。
https://codereview.stackexchange.com/questions/1942
复制相似问题