# Unable to Serial.read char while also trying to Serial.parseInt

**URL:** <https://forum.arduino.cc/t/unable-to-serial-read-char-while-also-trying-to-serial-parseint/691162>\
**Category:** Programming\
**Created:** [January 13, 2021, 9:40am UTC](https://forum.arduino.cc/t/unable-to-serial-read-char-while-also-trying-to-serial-parseint/691162 "2021-01-13T09:40:01Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![jaddow](https://avatars.discourse-cdn.com/v4/letter/j/ec9cab/32.png) [@jaddow](https://forum.arduino.cc/u/jaddow)\
**Post date:** [January 13, 2021, 9:40am UTC](https://forum.arduino.cc/t/unable-to-serial-read-char-while-also-trying-to-serial-parseint/691162/1 "2021-01-13T09:40:01Z")

</div>

Hi,  
I'm writing a program where you have to enter numbers between 0 - 1000. While you're doing this and you think you have enough data, you should be able to cancel this process and continue with the next step.  
I came up with two simple if-Statements but it seems like that, as soon as Serial.parseInt exists in the 2nd Statement, Serial.read cannot read any characters anymore.  
As soon as I delete the parseInt Statement, it workes just fine. Why is this so? Do you have any ideas how I could realize this?

The following code is an example Sketch I have created to mess around with my idea...

```cpp
char q;
void setup() {
  Serial.begin(9600);
  while(!Serial){
    }
  }
void loop() {
  char cInput = Serial.read();
  if (cInput == 'q'){
    Serial.println("Quit recieved");
    }
  int nInput = Serial.parseInt();
  if (nInput > 0){
    Serial.println("Data recieved");
    }
  }

```

---

<div class="post-metadata">

**Author:** ![UKHeliBob](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/ukhelibob/32/215663_2.png) [@UKHeliBob](https://forum.arduino.cc/u/UKHeliBob)\
**Post date:** [January 13, 2021, 9:43am UTC](https://forum.arduino.cc/t/unable-to-serial-read-char-while-also-trying-to-serial-parseint/691162/2 "2021-01-13T09:43:24Z")

</div>

> it seems like that, as soon as Serial.parseInt exists in the 2nd Statement, Serial.read cannot read any characters anymore.

Serial.parseInt() is a blocking function and until entry is complete or the timeout occurs no other code will run

Take a look at [Serial input basics - updated](http://forum.arduino.cc/index.php?topic=396450) for better ways to input data

---

<div class="post-metadata">

**Author:** ![johnwasser](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/johnwasser/32/214270_2.png) [@johnwasser](https://forum.arduino.cc/u/johnwasser)\
**Post date:** [January 13, 2021, 6:38pm UTC](https://forum.arduino.cc/t/unable-to-serial-read-char-while-also-trying-to-serial-parseint/691162/3 "2021-01-13T18:38:39Z")

</div>

More importantly, .parseInt() will throw away any characters it reads before it finds something that looks like the beginning of a number ('0'-'9', '-', maybe '+'). You can use Serial.peek() to see what character is coming next and only call '.parseInt()' if the next character is part of a number.

```cpp
  if (isDigit(Serial.peek()) || Serial.peek() == '+' || Serial.peek() == '-')
  {
  int nInput = Serial.parseInt();
  if (nInput > 0){
    Serial.println("Data recieved");
    }
  }

```

---

<div class="post-metadata">

**Author:** ![drmpf](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/drmpf/32/1126438_2.png) [@drmpf](https://forum.arduino.cc/u/drmpf)\
**Post date:** [January 14, 2021, 8:13pm UTC](https://forum.arduino.cc/t/unable-to-serial-read-char-while-also-trying-to-serial-parseint/691162/4 "2021-01-14T20:13:53Z")

</div>

Below is a simple general purpose program to read commands and numbers using the [SafeString library](https://www.forward.com.au/pfod/ArduinoProgramming/SafeString/index.html)  
Some sample output is

```cpp
 Input either stop or start cmds or an integer
stop
 Found stop cmd
kdfj  !!Invalid input!! 

33.3
 !!Invalid input!! 
33a
 !!Invalid input!! 
334

New Int:334

```

It uses a non-blocking SafeStringReader to collect and tokenize the input and the SafeString.toInt() method to convert the ints

The SafeString.toInt() has a number of advantages over the Arduino toInt()

- SafeString.toInt() rejects numbers like 33a
- When SafeString.toInt() finds a invalid number it returns false and the int argument is left unchanged, the Arduino toInt() returns 0 as the converted number with no other indication of failure. So you cannot tell if the number was actually 0 or just invalid

```cpp
// ReadCmdsAndNumbers.ino
//
// Example of NON-Blocking read commmands from the Arduino Monitor input and acts on them
// the available commands are start stop
// Commands are delimited by space dot comma NL or CR
// If you set the Arduino Monitor to No line ending then the last command will be ignored until it is terminated by a space or ,
//  Use the settings Newline or Carrage Return or Both NL & CR
//
// These commands can be picked out of a line of user input
// start  stop
// The input line can be as long as you like 100's of Kb long, but only two small buffers need to parse the commands
//
// download and install the SafeString library from
// www.forward.com.au/pfod/ArduinoProgramming/SafeString/index.html
#include "SafeStringReader.h"

// create an sfReader instance of SafeStringReader class
// that will handle commands upto 20 chars long , for numbers
// delimited by space, comma or CarrageReturn or NewLine
// the createSafeStringReader( ) macro creates both the SafeStringReader (sfReader) and the necessary SafeString that holds input chars until a delimiter is found
// args are (ReaderInstanceName, expectedMaxCmdLength, delimiters)
createSafeStringReader(sfReader, 20, " ,\r\n");

int intValue = 0;

void setup() {
  Serial.begin(9600);
  for (int i = 10; i > 0; i--) { // pause a little to give you time to open the Arduino monitor
    Serial.print(i); Serial.print(' '); delay(500);
  }
  Serial.println();
  Serial.println(" Input either stop or start cmds or an integer");
  SafeString::setOutput(Serial); // enable error messages and SafeString.debug() output to be sent to Serial
  sfReader.connect(Serial); // where SafeStringReader will read from
  sfReader.echoOn(); // echo back all input, by default echo is off
}

void handleStartCmd() {
  Serial.println(F(" Found start cmd"));
}
void handleStopCmd() {
  Serial.println(F(" Found stop cmd"));
}

void loop() {
  if (sfReader.read()) {         // non blocking read of input
    if (sfReader == "start") {
      handleStartCmd();
    } else if (sfReader == "stop") {
      handleStopCmd();
    } else if (sfReader.toInt(intValue)) {
        // got a new valid int
        Serial.println(); Serial.print("New Int:"); Serial.println(intValue);
    } else { // dont recognize this
      Serial.println(" !!Invalid input!! ");
    }
  } // else no delimited command yet

  // rest of code here is executed while the user typing in commands
}

```

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [May 14, 2021, 8:14pm UTC](https://forum.arduino.cc/t/unable-to-serial-read-char-while-also-trying-to-serial-parseint/691162/5 "2021-05-14T20:14:50Z")

</div>

Closed on May 14, 2021, 8:14pm UTC

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.
