// ArduinoStringToInt.ino // Converts Arduino String to an int using String.toInt() // https://www.forward.com.au/pfod/ArduinoProgramming/SerialReadingParsing/index.html // // Pros: Fairly robust catches invalid numbers // Cons: Need to trim() String first. Does not handle leading zeros, i.e. "0044" flagged as invalid void setup() { Serial.begin(9600); for (int i = 10; i > 0; i--) { Serial.print(' '); Serial.print(i); delay(500); } Serial.println(); Serial.println(F("ArduinoStringToInt.ino")); String numStr = " 43 "; numStr.trim(); // need to remove leading and trailing white space for the check to work int result = numStr.toInt(); // Arduino toInt() actually returns a long assigning to an int can be invalid for large numbers if (numStr == String(result)) { Serial.print(F(" result = ")); Serial.println(result); } else { Serial.print(F("Not a valid integer '")); Serial.print(numStr); Serial.println("'"); } } void loop() { // put your main code here, to run repeatedly: }