Home ArduinoArduino Tutorials Tutorial: Arduino Strings

Tutorial: Arduino Strings

by shedboy71

In Arduino, Strings are used to handle text data such as words, sentences, or characters.

Strings can be manipulated in various ways to create powerful and dynamic applications.

This tutorial explains the types of Strings in Arduino, their methods, and how to use them effectively with examples.

Table of Contents

1. What Are Strings in Arduino?

Strings are sequences of characters used to represent text. They are commonly used in Arduino for:

  • Displaying messages on Serial Monitor or LCDs.
  • Handling user input from sensors or communication devices.

2. Types of Strings

2.1 Character Arrays (C-style Strings)

  • Represented as an array of characters.
  • Null-terminated (\0) to indicate the end of the string.
  • More memory-efficient but harder to manipulate.

2.2 Arduino String Class

  • A built-in class that provides an easier way to manipulate strings.
  • Less efficient but more user-friendly.

3. Working with Character Arrays

3.1 Declaring and Using Character Arrays

Example: Declare and Print a Character Array

void setup() {
  Serial.begin(9600);

  char greeting[] = "Hello, Arduino!";
  Serial.println(greeting);  // Print the character array
}

void loop() {
  // Empty
}

3.2 Common Functions for Character Arrays

Concatenation

void setup() {
  Serial.begin(9600);

  char first[] = "Hello";
  char second[] = "World";
  char result[20];

  strcpy(result, first);  // Copy first to result
  strcat(result, " ");    // Append a space
  strcat(result, second); // Append second to result

  Serial.println(result);
}

void loop() {
  // Empty
}

String Length

void setup() {
  Serial.begin(9600);

  char text[] = "Arduino";
  int length = strlen(text);  // Get the length of the string

  Serial.print("Length: ");
  Serial.println(length);
}

void loop() {
  // Empty
}

4. Working with Arduino String Class

4.1 Declaring and Using Strings

Example: Declare and Print a String

void setup() {
  Serial.begin(9600);

  String greeting = "Hello, Arduino!";
  Serial.println(greeting);  // Print the string
}

void loop() {
  // Empty
}

4.2 String Functions and Methods

Concatenation

void setup() {
  Serial.begin(9600);

  String first = "Hello";
  String second = "World";
  String result = first + " " + second;  // Concatenate strings

  Serial.println(result);
}

void loop() {
  // Empty
}

Get String Length

void setup() {
  Serial.begin(9600);

  String text = "Arduino";
  Serial.print("Length: ");
  Serial.println(text.length());
}

void loop() {
  // Empty
}

Compare Strings

void setup() {
  Serial.begin(9600);

  String a = "Arduino";
  String b = "Arduino";

  if (a.equals(b)) {
    Serial.println("Strings are equal");
  } else {
    Serial.println("Strings are not equal");
  }
}

void loop() {
  // Empty
}

Substring

void setup() {
  Serial.begin(9600);

  String text = "Hello, Arduino!";
  String part = text.substring(7, 14);  // Extract "Arduino"

  Serial.println(part);
}

void loop() {
  // Empty
}

Convert to Upper/Lower Case

void setup() {
  Serial.begin(9600);

  String text = "Arduino";
  text.toUpperCase();
  Serial.println(text);  // Output: ARDUINO

  text.toLowerCase();
  Serial.println(text);  // Output: arduino
}

void loop() {
  // Empty
}

5. Practical Examples

Example 5.1: Read and Display Input from Serial Monitor

String inputString = "";  // A string to hold incoming data

void setup() {
  Serial.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    inputString = Serial.readString();  // Read input
    Serial.print("You entered: ");
    Serial.println(inputString);        // Echo input back
  }
}

Example 5.2: Parse Sensor Data

String data = "Temperature=25;Humidity=60";

void setup() {
  Serial.begin(9600);

  int tempIndex = data.indexOf("Temperature=") + 12;
  int tempEnd = data.indexOf(";", tempIndex);
  String temperature = data.substring(tempIndex, tempEnd);

  int humIndex = data.indexOf("Humidity=") + 9;
  String humidity = data.substring(humIndex);

  Serial.print("Temperature: ");
  Serial.println(temperature);
  Serial.print("Humidity: ");
  Serial.println(humidity);
}

void loop() {
  // Empty
}

Example 5.3: Control LED Using Serial Input

const int ledPin = 13;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
  Serial.println("Type 'ON' or 'OFF' to control the LED.");
}

void loop() {
  if (Serial.available() > 0) {
    String command = Serial.readString();
    command.trim();  // Remove leading/trailing spaces

    if (command.equalsIgnoreCase("ON")) {
      digitalWrite(ledPin, HIGH);
      Serial.println("LED is ON");
    } else if (command.equalsIgnoreCase("OFF")) {
      digitalWrite(ledPin, LOW);
      Serial.println("LED is OFF");
    } else {
      Serial.println("Invalid command");
    }
  }
}

6. Best Practices for Using Strings

  1. Use Character Arrays for Efficiency:
    • Prefer character arrays for memory-critical applications as they are more efficient.
  2. Avoid Excessive String Concatenation:
    • Minimize repeated concatenations with String objects, as they can cause memory fragmentation.
  3. Trim Input:
    • Use trim() to remove unwanted whitespace from user input.
  4. Use Adequate Buffer Sizes:
    • When using character arrays, allocate enough space to include the null terminator (\0).
  5. Test for Edge Cases:
    • Ensure that your string handling logic works for empty strings, long inputs, and unexpected formats.

Conclusion

Strings in Arduino allow you to handle and manipulate text data efficiently. By choosing between character arrays and the Arduino String class based on your application’s requirements, you can create robust and memory-efficient programs.

This tutorial covers the essential methods and examples to help you get started with strings in Arduino.

For more details, visit the official Arduino reference.

 

You may also like