// ReadToInt_String.ino // Non-blocking read of a newline terminated integer and convert to interger // uses Arduino String to collect input line and compare result to String.toInt() // https://www.forward.com.au/pfod/ArduinoProgramming/SerialReadingParsing/index.html // // Pros: Fairly robust catches invalid numbers // Cons: Input needs to be terminated by newline. Does not handle leading zeros, i.e. "0044" flagged as invalid String numStrInput; int number; void setup() { Serial.begin(9600); for (int i = 10; i > 0; i--) { Serial.print(' '); Serial.print(i); delay(500); } Serial.println(); Serial.println(F("ReadToInt_String.ino")); Serial.println(F(" Enter numbers - one per line, IDE monitor set to newline")); numStrInput.reserve(25); // see Taming Arduino Strings // https://www.forward.com.au/pfod/ArduinoProgramming/ArduinoStrings/index.html} } // read Serial until until_c char found, returns true when found else false // non-blocking, until_c is returned as last char in String, updates input String with chars read bool readStringUntil(String& input, char until_c) { while (Serial.available()) { char c = Serial.read(); input += c; if (c == until_c) { return true; } } return false; } // returns false most of the time // only returns true when new valid int read in and converted and result stored // NOTE: does not update result until a new valid integer read in and converted // invalid inputs print error msg to Serial bool readIntNonBlocking(int& result) { if (readStringUntil(numStrInput, '\n')) { // got a line bool numberValid = false; // try and convert to int numStrInput.trim(); int num = numStrInput.toInt(); // Arduino toInt() actually returns a long assigning to an int can be invalid for large numbers if (numStrInput == String(num)) { numberValid = true; // valid so update the result result = num; //Serial.print(F(" result = ")); Serial.println(result); } else { Serial.print(F("Not a valid integer '")); Serial.print(numStrInput); Serial.println("'"); } numStrInput = ""; // clear after processing, for next line return numberValid; } return false; // still reading in line so no new number } void loop() { if (readIntNonBlocking(number)) { // got a new valid number input Serial.print(F(" got a new valid number:")); Serial.println(number); } }