| 1 |
/* |
| 2 |
String to Integer conversion |
| 3 |
|
| 4 |
Reads a serial input string until it sees a newline, then converts the string |
| 5 |
to a number if the characters are digits. |
| 6 |
|
| 7 |
The circuit: |
| 8 |
- No external components needed. |
| 9 |
|
| 10 |
created 29 Nov 2010 |
| 11 |
by Tom Igoe |
| 12 |
|
| 13 |
This example code is in the public domain. |
| 14 |
|
| 15 |
https://www.arduino.cc/en/Tutorial/BuiltInExamples/StringToInt |
| 16 |
*/ |
| 17 |
|
| 18 |
String inString = ""; // string to hold input |
| 19 |
|
| 20 |
void setup() { |
| 21 |
// Open serial communications and wait for port to open: |
| 22 |
Serial.begin(9600); |
| 23 |
while (!Serial) { |
| 24 |
; // wait for serial port to connect. Needed for native USB port only |
| 25 |
} |
| 26 |
|
| 27 |
// send an intro: |
| 28 |
Serial.println("\n\nString toInt():"); |
| 29 |
Serial.println(); |
| 30 |
} |
| 31 |
|
| 32 |
void loop() { |
| 33 |
// Read serial input: |
| 34 |
while (Serial.available() > 0) { |
| 35 |
int inChar = Serial.read(); |
| 36 |
if (isDigit(inChar)) { |
| 37 |
// convert the incoming byte to a char and add it to the string: |
| 38 |
inString += (char)inChar; |
| 39 |
} |
| 40 |
// if you get a newline, print the string, then the string's value: |
| 41 |
if (inChar == '\n') { |
| 42 |
Serial.print("Value:"); |
| 43 |
Serial.println(inString.toInt()); |
| 44 |
Serial.print("String: "); |
| 45 |
Serial.println(inString); |
| 46 |
// clear the string for new input: |
| 47 |
inString = ""; |
| 48 |
} |
| 49 |
} |
| 50 |
} |