Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

arduino - serial.parseInt() returns a 0 value on its own

I am trying to read some integers from serial, so I used Serial.parseInt() to read two values(0 or 1), the thing is the code runs perfectly for the first time, but then the serial start reading the value 0 on its own, without me sending anything, here is part of the code I am using:

while (!Serial.available()) {}
A = Serial.parseInt();
Serial.println(A);
if (A == 1) {
  Book = "";
  Serial.println("add tag");
  while (Book == "") {
    delay(2000);
    Book = tagB();
  }
  Serial.println(Book);
  sendToE1("", Book);
  delay(2000);
}
}
}
question from:https://stackoverflow.com/questions/65947991/serial-parseint-returns-a-0-value-on-its-own

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Serial.parseInt returns 0 when it times out with none or invalid characters received.

As you're loop is waiting for available data befor you call Serial.parseInt the only explanation is that you're sending something else but numbers. Most likely a linefeed or carriage return from your terminal program or a println function...

You should probably call Serial.peek to check if the next byte is a number befor you call Serial.parseInt. If you know for sure that you did not send anything but that single integer and some non-numeric character you can also clear the input buffer befor parsing a possible next integer.

But if you're sending an integer and a termination character you might as well just not use Serial.parseInt. Read your data into an array until you receive the termination character. Then convert your data to an integer yourself.

Using Serial.parseInt only makes sense if you know you're about to receive an integer representation within a certain time interval.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...