2010-11-29 19:59:09 +01:00
|
|
|
/*
|
|
|
|
String to Integer conversion
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2017-07-14 21:34:00 +02:00
|
|
|
Reads a serial input string until it sees a newline, then converts the string
|
|
|
|
to a number if the characters are digits.
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2017-07-15 00:30:34 +02:00
|
|
|
The circuit:
|
2017-07-12 22:18:23 +02:00
|
|
|
- No external components needed.
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2017-07-15 00:30:34 +02:00
|
|
|
created 29 Nov 2010
|
|
|
|
by Tom Igoe
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2017-07-15 00:30:34 +02:00
|
|
|
This example code is in the public domain.
|
2017-07-12 22:18:23 +02:00
|
|
|
|
|
|
|
http://www.arduino.cc/en/Tutorial/StringToInt
|
2017-07-15 00:35:58 +02:00
|
|
|
*/
|
2010-11-29 19:59:09 +01:00
|
|
|
|
|
|
|
String inString = ""; // string to hold input
|
|
|
|
|
|
|
|
void setup() {
|
2012-04-06 12:59:54 +02:00
|
|
|
// Open serial communications and wait for port to open:
|
2010-11-29 19:59:09 +01:00
|
|
|
Serial.begin(9600);
|
2012-04-06 20:00:31 +02:00
|
|
|
while (!Serial) {
|
2015-09-21 14:44:19 +02:00
|
|
|
; // wait for serial port to connect. Needed for native USB port only
|
2012-04-06 20:00:31 +02:00
|
|
|
}
|
2012-04-06 12:59:54 +02:00
|
|
|
|
2012-04-06 20:00:31 +02:00
|
|
|
// send an intro:
|
2012-04-06 12:59:54 +02:00
|
|
|
Serial.println("\n\nString toInt():");
|
2012-04-06 20:00:31 +02:00
|
|
|
Serial.println();
|
2010-11-29 19:59:09 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
void loop() {
|
|
|
|
// Read serial input:
|
|
|
|
while (Serial.available() > 0) {
|
|
|
|
int inChar = Serial.read();
|
|
|
|
if (isDigit(inChar)) {
|
2017-07-14 21:34:00 +02:00
|
|
|
// convert the incoming byte to a char and add it to the string:
|
2013-10-21 09:58:40 +02:00
|
|
|
inString += (char)inChar;
|
2010-11-29 19:59:09 +01:00
|
|
|
}
|
2017-07-14 21:34:00 +02:00
|
|
|
// if you get a newline, print the string, then the string's value:
|
2010-11-29 19:59:09 +01:00
|
|
|
if (inChar == '\n') {
|
|
|
|
Serial.print("Value:");
|
|
|
|
Serial.println(inString.toInt());
|
|
|
|
Serial.print("String: ");
|
|
|
|
Serial.println(inString);
|
|
|
|
// clear the string for new input:
|
2013-10-21 09:58:40 +02:00
|
|
|
inString = "";
|
2010-11-29 19:59:09 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|