[英]How to store serial inputs in an char array arduino?
My aim was getting some parts of a char array between 2 specified characters.我的目标是在 2 个指定字符之间获取 char 数组的某些部分。 The code below perfectly works and returns 0037 as I expected.
下面的代码完美运行,并按我的预期返回 0037。 However I wanted to make it useable with serial input not only char*s.
但是我想让它不仅可用于 char*s 的串行输入。 In other words if I write "123123123,0037sjd#asdasdasd" to the serial.
换句话说,如果我在连续剧中写“123123123,0037sjd#asdasdasd”。 the code should work in a same way again.
代码应该再次以相同的方式工作。
How can I do that?我怎样才能做到这一点?
const char *s = "123123123!0037sjd#asdasdasd";
const char *CHAR1 = "!";
const char *CHAR2 = "#";
char *target = NULL;
char *start, *end;
void setup() {
Serial.begin(9600);
}
void loop() {
//s=(char)Serial.read();
if (start = strstr(s, CHAR1)) {
start += strlen(CHAR1);
if (end = strstr(start, CHAR2)) {
target = (char*) malloc(end - start + 1);
memcpy(target, start, end - start);
target[end - start] = '\0';
}
}
if (target) {
for (int i = 0; i < 4; i++) {
Serial.print(target[i]);
}
target = "";
free(target);
}
target = "";
free(target);
}
Assignment loses original allocation.分配丢失原始分配。
Code errantly free's something not allocated.代码错误地免费的东西没有分配。
// Bad
target=""; // loses prior allocation
free( target ); // Attempts to free something not allocated
Instead反而
free( target );
target = NULL;
For parsing a serial stream like that, maybe just use a flag.为了像这样解析串行 stream ,也许只使用一个标志。 Start off with the flag cleared.
从清除标志开始。 When you see a !
当你看到一个! set the flag.
设置标志。 When digits come in while the flag is set, store them in the array.
在设置标志的同时输入数字时,将它们存储在数组中。 When you see something that's not a digit, clear the flag.
当你看到不是数字的东西时,清除标志。
You could even accumulate the digits in an integer on the fly (skipping the array), if that's what the end result will be.如果最终结果是这样的话,您甚至可以在 integer 中即时累积数字(跳过数组)。
Personally, I don't use malloc/free on the Arduino, and it's not really needed here.就个人而言,我不在 Arduino 上使用 malloc/free,这里也不需要。
HTH! HTH!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.