Debian Codegraph @

examples/08.Strings/StringLength/StringLength.ino

raw
1 /*
2 String length()
3
4 Examples of how to use length() in a String.
5 Open the Serial Monitor and start sending characters to see the results.
6
7 created 1 Aug 2010
8 by Tom Igoe
9
10 This example code is in the public domain.
11
12 https://www.arduino.cc/en/Tutorial/BuiltInExamples/StringLengthTrim
13 */
14
15 String txtMsg = ""; // a string for incoming text
16 unsigned int lastStringLength = txtMsg.length(); // previous length of the String
17
18 void setup() {
19 // Open serial communications and wait for port to open:
20 Serial.begin(9600);
21 while (!Serial) {
22 ; // wait for serial port to connect. Needed for native USB port only
23 }
24
25 // send an intro:
26 Serial.println("\n\nString length():");
27 Serial.println();
28 }
29
30 void loop() {
31 // add any incoming characters to the String:
32 while (Serial.available() > 0) {
33 char inChar = Serial.read();
34 txtMsg += inChar;
35 }
36
37 // print the message and a notice if it's changed:
38 if (txtMsg.length() != lastStringLength) {
39 Serial.println(txtMsg);
40 Serial.println(txtMsg.length());
41 // if the String's longer than 140 characters, complain:
42 if (txtMsg.length() < 140) {
43 Serial.println("That's a perfectly acceptable text message");
44 } else {
45 Serial.println("That's too long for a text message.");
46 }
47 // note the length for next time through the loop:
48 lastStringLength = txtMsg.length();
49 }
50 }