This example is for Wiring version 1.0 build 0100+. If you have a previous version, use the examples included with your software. If you see any errors or have comments, please let us know.
String toInt() by Tom Igoe
Reads a serial input string until it sees a newline, then converts the string to a number if the characters are digits.
Reads a serial input string until it sees a newline, then converts the string to a number if the characters are digits.
String inString = ""; // string to hold input void setup() { // Initialize serial communications: Serial.begin(9600); } void loop() { // Read serial input: while (Serial.available() > 0) { int inChar = Serial.read(); if (isDigit(inChar)) { // convert the incoming byte to a char // and add it to the string: inString += (char)inChar; } // if you get a newline, print the string, // then the string's value: if (inChar == '\n') { Serial.print("Value:"); Serial.println(inString.toInt()); Serial.print("String: "); Serial.println(inString); // clear the string for new input: inString = ""; } } }
