簡體   English   中英

如何將串行輸入存儲在字符數組 arduino 中?

[英]How to store serial inputs in an char array arduino?

我的目標是在 2 個指定字符之間獲取 char 數組的某些部分。 下面的代碼完美運行,並按我的預期返回 0037。 但是我想讓它不僅可用於 char*s 的串行輸入。 換句話說,如果我在連續劇中寫“123123123,0037sjd#asdasdasd”。 代碼應該再次以相同的方式工作。

我怎樣才能做到這一點?

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);
}

分配丟失原始分配。

代碼錯誤地免費的東西沒有分配。

// Bad
target="";        // loses prior allocation
free( target );   // Attempts to free something not allocated

反而

free( target );
target = NULL;

為了像這樣解析串行 stream ,也許只使用一個標志。 從清除標志開始。 當你看到一個 設置標志。 在設置標志的同時輸入數字時,將它們存儲在數組中。 當你看到不是數字的東西時,清除標志。

如果最終結果是這樣的話,您甚至可以在 integer 中即時累積數字(跳過數組)。

就個人而言,我不在 Arduino 上使用 malloc/free,這里也不需要。

HTH!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM