簡體   English   中英

奇怪的 C++ Arduino 串行行為

[英]Strange C++ Arduino serial behavior

我正在為我的 arduino 編寫一些代碼來打印 4 個按鈕狀態和來自模擬操縱桿的 X、Y 坐標,但我有奇怪的行為。

這是代碼:

  int x,y;
  x = analogRead(joy_x);
  y = analogRead(joy_y);
  char* buf = new char[4];
  sprintf(buf, "%4d", x);
  Serial.print("X:");
  Serial.print(buf);
  Serial.print(" Y:");
  sprintf(buf, "%4d", y);
  Serial.println(buf);

  int one,two,three,four;
  one = digitalRead(touchOne);
  two = digitalRead(touchTwo);
  three = digitalRead(touchThree);
  four = digitalRead(touchFour);

  // create an array of states set to the default values
  char states[4] = {'X', 'X', 'X', 'X'};
  // change each value if it is not in the default state
  if(one   == 1) states[0] = 'O';
  if(two   == 1) states[1] = 'O';
  if(three == 1) states[2] = 'O';
  if(four  == 1) states[3] = 'O';
  // output the states to the OLED display
  //display.print(states);
  Serial.print(states);

當它運行時,串行輸出如下所示:

XXXX3X: 515 Y: 520
XXXX3X: 516 Y: 520
XXXX3X: 516 Y: 519
XXXX3X: 516 Y: 520
XXXX3X: 515 Y: 520
XXXX3X: 516 Y: 519
XXXX3X: 516 Y: 520
XXXX3X: 515 Y: 519
XXXX3X: 516 Y: 520

即使 X、Y 應該在 XXXX 之前,並且數字 3 突然出現。 希望能解開這個謎,謝謝。

代碼中有多個緩沖區溢出。

  char* buf = new char[4];
  sprintf(buf, "%4d", x);
  ...
  sprintf(buf, "%4d", y);

這需要為sprintf添加的空終止符sprintf

  char* buf = new char[5];

也更容易:這里沒有必要使用免費商店。

  char buf[5];

同樣的事情在這里:

  char states[4] = {'X', 'X', 'X', 'X'};
  ...
  Serial.print(states);

我們需要添加一個空終止符以使其成為有效的字符串。

  char states[5] = {'X', 'X', 'X', 'X', '\0'};

這應該處理直接的內存問題。

暫無
暫無

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

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