Arduino - How to Fix - parseInt returns 0

preview_player
Показать описание
What to do if the Arduino parseInt function always returns an additional 0 when you send a number? Quick fix + explanation in 3 minutes.

0:00 Getting an additional 0 with parseInt
0:19 The code with parseInt()
0:57 The reason why you have this additional 0
2:17 Fix the problem
3:28 Outro

Рекомендации по теме
Комментарии
Автор

Sorry, but this doesn't work for me....
Even with No line ending, I still get a trailing 0.
It's likely because when the string has a \0 attached at the end to
signify the string terminates.
Here's my code...

void setup() {
Serial.begin(9600);
Serial.println("This program pick out all ints from a string");
// Suggested string to Parse: Gamer04 played 16, won 08 and drew 2 games
// the 0 of "04" will be left off because as an int, 04 is = just '4'
}

void loop() {
while (Serial.available() == 0) {}
int MyDataInput = Serial.parseInt(); // parseInt scans a string for a integer
Serial.println(MyDataInput);
delay(2000);
}

kychemclass
Автор

Thanks quick questions if you would like to do the same thing but instead of communicating through one arduino through two arduinos how would you take off
the extra zeros

emilevachon
Автор

Thank you Edouard, I didn't realise we could modify the line endings like that. Trouble is, the sketch might be copied to another host, and one must always remember to change that setting. I had created a loop that just 'drains' the surplus byte(s) and discards them.
With all due respect I think my approach is more flexible, as it will always work regardless of the end-of-line settings. Of course it will also work if the no-line-endings option is set.

while (Serial.available() < 1)
delay(300);
char chInput = Serial.read(); // Store the input we are interested in, and drain the rest
// Serial input always adds extra input character(s), a CR or NL
// This causes the prompt to reappear after clicking Send. So loop through
// the input queue and drain it.
while (Serial.available() > 0)
Serial.read();

... // Do something with chInput

sholtodouglas
Автор

Good day! how about if it sends Zero first before displaying the input number? How could we fix that case?

jackandersonmelgar
join shbcf.ru