2010-08-01 16:18:31 +02:00
|
|
|
/*
|
2013-10-21 09:58:40 +02:00
|
|
|
String length()
|
|
|
|
|
|
|
|
Examples of how to use length() in a String.
|
2010-08-01 16:18:31 +02:00
|
|
|
Open the Serial Monitor and start sending characters to see the results.
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2010-08-01 16:18:31 +02:00
|
|
|
created 1 Aug 2010
|
|
|
|
by Tom Igoe
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2010-08-11 23:56:28 +02:00
|
|
|
http://arduino.cc/en/Tutorial/StringLengthTrim
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2010-08-01 16:18:31 +02:00
|
|
|
This example code is in the public domain.
|
|
|
|
*/
|
2012-10-18 19:03:25 +02:00
|
|
|
|
2010-08-01 16:18:31 +02:00
|
|
|
String txtMsg = ""; // a string for incoming text
|
2010-08-10 21:33:52 +02:00
|
|
|
int lastStringLength = txtMsg.length(); // previous length of the String
|
2010-08-01 16:18:31 +02:00
|
|
|
|
|
|
|
void setup() {
|
2012-04-06 12:59:54 +02:00
|
|
|
// Open serial communications and wait for port to open:
|
2010-08-01 16:18:31 +02:00
|
|
|
Serial.begin(9600);
|
2012-04-06 20:00:31 +02:00
|
|
|
while (!Serial) {
|
|
|
|
; // wait for serial port to connect. Needed for Leonardo only
|
|
|
|
}
|
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 length():");
|
2012-06-26 01:01:52 +02:00
|
|
|
Serial.println();
|
2010-08-01 16:18:31 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
void loop() {
|
|
|
|
// add any incoming characters to the String:
|
|
|
|
while (Serial.available() > 0) {
|
|
|
|
char inChar = Serial.read();
|
|
|
|
txtMsg += inChar;
|
2013-10-21 09:58:40 +02:00
|
|
|
}
|
2010-08-01 16:18:31 +02:00
|
|
|
|
|
|
|
// print the message and a notice if it's changed:
|
|
|
|
if (txtMsg.length() != lastStringLength) {
|
|
|
|
Serial.println(txtMsg);
|
|
|
|
Serial.println(txtMsg.length());
|
|
|
|
// if the String's longer than 140 characters, complain:
|
|
|
|
if (txtMsg.length() < 140) {
|
|
|
|
Serial.println("That's a perfectly acceptable text message");
|
2013-10-21 09:58:40 +02:00
|
|
|
}
|
2010-08-01 16:18:31 +02:00
|
|
|
else {
|
2013-10-21 09:58:40 +02:00
|
|
|
Serial.println("That's too long for a text message.");
|
2010-08-01 16:18:31 +02:00
|
|
|
}
|
|
|
|
// note the length for next time through the loop:
|
|
|
|
lastStringLength = txtMsg.length();
|
|
|
|
}
|
2012-04-06 12:59:54 +02:00
|
|
|
}
|