Ugenz Academy/IoT Tutorial

Arrays And Strings

19 min read3,755 words

Reading progress

Keep learning

Arrays and Strings in ESP32 Programming

1. Introduction

When programming an ESP32, you often need to store multiple values, process sensor readings, handle text commands, and exchange information with other devices. Arrays and strings help you manage this information efficiently.

For example, imagine an ESP32 monitoring five temperature readings. Creating five separate variables works, but managing them becomes difficult as the number of readings increases. An array lets you store all the readings under one variable name.

Similarly, if your ESP32 hosts a web server, it may need to process text such as device names, HTTP requests, status messages, and user commands. Strings and character arrays help handle this text.

In this lesson, you will learn arrays and strings from the basics through practical embedded programming applications.

2. What Is an Array?

An array is a collection of elements of the same data type stored under one variable name.

Instead of writing:

int sensor1 = 100; int sensor2 = 200; int sensor3 = 300; int sensor4 = 400;

You can write:

int sensorValues[4] = {100, 200, 300, 400};

Here:

  • int specifies the type of each element.
  • sensorValues is the array name.
  • [4] specifies the array's capacity.
  • The values inside {} initialize the array elements.

An array makes it easier to store, access, and process related data.

3. Understanding Array Indexes

Each array element has an index that identifies its position. In C++, array indexing begins at 0, not 1.

Consider:

int values[5] = {10, 20, 30, 40, 50};

The indexes are:

IndexValue
010
120
230
340
450

The first element is values[0], and the last element is values[4].

For an array containing N elements, valid indexes range from 0 to N - 1.

Important: Accessing an element outside the valid range causes undefined behavior in C++. It can lead to incorrect results, memory corruption, or crashes.

4. Declaring and Initializing Arrays

Declaring an array

You can declare an array by specifying its data type, name, and size.

int readings[5];

This creates an array with five integer elements. Because it is a local array without initialization, its elements have indeterminate values. Initialize the array before reading its contents.

Initializing an array

You can provide initial values when declaring the array.

int readings[5] = {100, 200, 300, 400, 500};

You can also let the compiler determine the number of elements:

int readings[] = {100, 200, 300, 400, 500};

In this case, the compiler determines that the array contains five elements.

Initializing elements with zero

int readings[5] = {};

All elements are initialized to zero.

This is useful when you want to collect measurements later and begin with known values.

5. Accessing and Modifying Array Elements

You can read or change an element using its index.

int sensorValues[3] = {100, 200, 300}; void setup() { Serial.begin(115200); Serial.println(sensorValues[0]); Serial.println(sensorValues[1]); sensorValues[2] = 500; Serial.println(sensorValues[2]); } void loop() { }

Output:

100 200 500

The statement sensorValues[2] = 500; replaces the third element's original value with 500.

Arrays are useful when collecting sensor readings, storing configuration values, managing output states, or processing a fixed number of measurements.

6. Using Loops with Arrays

Loops allow you to process array elements without writing a separate statement for every element.

int sensorValues[5] = {100, 200, 300, 400, 500}; void setup() { Serial.begin(115200); for (int i = 0; i < 5; i++) { Serial.print("Sensor value: "); Serial.println(sensorValues[i]); } } void loop() { }

The for loop processes each element in order.

  • int i = 0 initializes the index.
  • i < 5 keeps the loop running while the index is valid.
  • i++ increments the index after each iteration.
  • sensorValues[i] accesses the current element.

This approach is much easier to maintain than writing five separate print statements.

Avoiding hard-coded array sizes

For a fixed array in the same scope, you can calculate the number of elements using sizeof.

int sensorValues[] = {100, 200, 300, 400, 500}; void setup() { Serial.begin(115200); size_t count = sizeof(sensorValues) / sizeof(sensorValues[0]); for (size_t i = 0; i < count; i++) { Serial.println(sensorValues[i]); } } void loop() { }

The expression divides the total array size in bytes by the size of one element.

This technique works when sensorValues is an actual array. When an array is passed to a function as a pointer, sizeof does not provide the original array length. In that case, pass the element count separately or use an appropriate container.

7. Calculating the Sum and Average of an Array

Arrays are especially useful when you need to process multiple sensor readings.

int readings[] = {20, 22, 24, 26, 28}; void setup() { Serial.begin(115200); const size_t count = sizeof(readings) / sizeof(readings[0]); long sum = 0; for (size_t i = 0; i < count; i++) { sum += readings[i]; } float average = static_cast<float>(sum) / count; Serial.print("Total: "); Serial.println(sum); Serial.print("Average: "); Serial.println(average); } void loop() { }

Output:

Total: 120 Average: 24.00

The program adds the readings and divides the total by the number of elements.

For real sensors, averaging several readings can help reduce the effect of short-term measurement fluctuations. However, averaging does not eliminate every type of sensor error.

8. Multidimensional Arrays

A multidimensional array contains other arrays. A two-dimensional array is often visualized as a table with rows and columns.

For example:

int readings[3][2] = { {20, 25}, {22, 27}, {24, 29} };

This array has three rows and two columns.

RowColumn 0Column 1
02025
12227
22429

You can access individual elements using two indexes.

readings[0][1]

This accesses the value 25.

Processing a two-dimensional array

int readings[3][2] = { {20, 25}, {22, 27}, {24, 29} }; void setup() { Serial.begin(115200); for (int row = 0; row < 3; row++) { for (int column = 0; column < 2; column++) { Serial.print(readings[row][column]); Serial.print(" "); } Serial.println(); } } void loop() { }

Output:

20 25 22 27 24 29

Multidimensional arrays can represent measurements from multiple sensors across multiple samples, lookup tables, or fixed layouts of data.

9. Arrays in ESP32 Applications

Arrays are useful for several embedded programming tasks.

Storing multiple sensor readings

float temperatures[4] = {25.2, 25.5, 26.0, 25.8};

Managing several LED pins

const int ledPins[] = {2, 4, 5, 18};

Storing a fixed sequence of output states

const int pattern[] = {1, 0, 1, 1, 0};

Recording a sequence of measurements

uint16_t measurements[10] = {};

The last example reserves space for ten 16-bit unsigned integer measurements and initializes all elements to zero.

Remember that arrays occupy memory. Choose an appropriate size, especially when working with large buffers or memory-constrained applications.

10. What Is a String?

A string is a sequence of characters used to represent text.

Examples include:

  • "ESP32"
  • "Ugenz Academy"
  • "Device connected"
  • "Temperature is high"

In C++ embedded programming, you will commonly encounter two approaches to text:

  1. C-style strings, which use character arrays terminated by '\0'.
  2. The Arduino String class, which provides convenient text-handling operations.

These approaches are related, but they are not the same.

11. Understanding Characters

The char type represents a character.

char letter = 'A'; char command = 'L'; char digit = '7';

A character literal uses single quotation marks.

A string literal uses double quotation marks:

char letter = 'A'; const char* message = "Hello";

The first example stores one character. The second points to a null-terminated sequence of characters.

A character can also be represented by a numeric character code.

char letter = 'A';

On ASCII-compatible systems, the code for uppercase A is 65.

Characters are important when processing commands received through serial communication, Bluetooth, or network connections.

12. C-Style Strings

A C-style string is a sequence of characters terminated by a special null character, written as '\0'.

Example:

char deviceName[] = "ESP32";

The array contains six characters in total:

'E' 'S' 'P' '3' '2' '\0'

The null terminator marks the end of the text. It is not the same as the character '0'.

Declaring a character array

char message[20] = "Hello ESP32";

This creates a character array with space for 20 characters, including the terminating null character.

The remaining elements are initialized to zero because the array is initialized using a shorter string literal.

Reading a C-style string

char deviceName[] = "ESP32"; void setup() { Serial.begin(115200); Serial.println(deviceName); } void loop() { }

Output:

ESP32

C-style strings are widely used in C and C++ libraries, low-level communication, and memory-conscious embedded applications.

13. Modifying Character Arrays

A mutable character array can be modified after initialization.

char message[] = "HELLO"; void setup() { Serial.begin(115200); message[0] = 'Y'; Serial.println(message); } void loop() { }

Output:

YELLO

The first character is replaced with Y.

However, this is not valid:

const char* message = "HELLO"; // message[0] = 'Y'; // Invalid: cannot modify through this pointer

A string literal should not be modified. Use a writable character array when you need to change individual characters.

14. C-Style String Length and Size

Consider this declaration:

char message[20] = "ESP32";

The array's capacity is 20 bytes, but the text length is 5 characters.

These are different concepts.

  • Capacity: How much space is allocated.
  • String length: How many characters occur before the null terminator.

You can use strlen() from <cstring> to calculate the length of a valid null-terminated C-style string.

#include <cstring> char message[] = "ESP32"; void setup() { Serial.begin(115200); Serial.print("Length: "); Serial.println(strlen(message)); Serial.print("Array size: "); Serial.println(sizeof(message)); } void loop() { }

Output:

Length: 5 Array size: 6

The array occupies six bytes because it includes the null terminator.

Do not call strlen() on a character buffer that is not guaranteed to contain a null terminator within its bounds. Doing so can cause an out-of-bounds read.

15. Common C-Style String Functions

C-style strings can be processed using standard library functions.

Include <cstring> when using the C++ string functions declared in that header.

strlen()

Returns the length of a null-terminated string, excluding the null terminator.

#include <cstring> char message[] = "ESP32"; size_t length = strlen(message);

The result is 5.

strcmp()

Compares two C-style strings.

#include <cstring> const char command[] = "ON"; void setup() { Serial.begin(115200); if (strcmp(command, "ON") == 0) { Serial.println("Command recognized"); } } void loop() { }

strcmp() returns zero when the strings are equal. It is case-sensitive, so "ON" and "on" are different strings.

strcpy()

Copies a C-style string into a destination buffer.

#include <cstring> char destination[20]; void setup() { Serial.begin(115200); strcpy(destination, "ESP32"); Serial.println(destination); } void loop() { }

Before copying, ensure that the destination buffer is large enough for all characters and the terminating null character. An undersized buffer can cause memory corruption.

strcat()

Appends one C-style string to another.

#include <cstring> char message[30] = "Hello "; const char name[] = "ESP32"; void setup() { Serial.begin(115200); strcat(message, name); Serial.println(message); } void loop() { }

Output:

Hello ESP32

The destination must have enough remaining capacity for the appended text and its null terminator.

16. The Arduino String Class

The Arduino String class provides a convenient way to create and manipulate text.

Example:

String deviceName = "ESP32"; String status = "Connected";

Unlike a fixed-size character array, an Arduino String can change its length dynamically.

This can make text operations easier, especially for beginners.

Combining strings

String device = "ESP32"; String message = device + " is connected"; void setup() { Serial.begin(115200); Serial.println(message); } void loop() { }

Output:

ESP32 is connected

Appending text

String message = "Temperature: "; void setup() { Serial.begin(115200); message += "28.5 C"; Serial.println(message); } void loop() { }

The += operator appends text to the existing string.

Getting the length

String message = "Ugenz Academy"; void setup() { Serial.begin(115200); Serial.println(message.length()); } void loop() { }

The output is 13, excluding any terminating null character used internally by the implementation.

17. Useful Arduino String Methods

The Arduino String class provides several useful methods.

MethodPurposeExample
length()Returns the text lengthmessage.length()
charAt(index)Returns a character at an indexmessage.charAt(0)
substring(start, end)Extracts part of a stringmessage.substring(0, 3)
indexOf()Searches for a character or substringmessage.indexOf("ESP")
startsWith()Checks the beginning of a stringmessage.startsWith("GET")
endsWith()Checks the end of a stringmessage.endsWith("ON")
toUpperCase()Converts text to uppercasemessage.toUpperCase()
toLowerCase()Converts text to lowercasemessage.toLowerCase()
trim()Removes leading and trailing whitespacemessage.trim()
replace()Replaces matching textmessage.replace("OFF", "ON")

Example:

String message = " esp32 connected "; void setup() { Serial.begin(115200); message.trim(); message.toUpperCase(); Serial.println(message); } void loop() { }

Output:

ESP32 CONNECTED

Methods such as toUpperCase(), toLowerCase(), trim(), and replace() modify the String object in place.

18. Comparing Strings

String comparison is important when an ESP32 receives commands.

Comparing Arduino strings

String command = "ON"; void setup() { Serial.begin(115200); if (command == "ON") { Serial.println("Turn the device on"); } } void loop() { }

Comparing C-style strings

Use strcmp() rather than == to compare the contents of C-style strings.

#include <cstring> const char command[] = "ON"; void setup() { Serial.begin(115200); if (strcmp(command, "ON") == 0) { Serial.println("Turn the device on"); } } void loop() { }

For C-style strings, comparing pointers with == checks whether the pointers refer to the same location, not whether the character sequences are equal.

19. Receiving Text Through Serial

An ESP32 can receive commands from a computer using the Serial Monitor.

The following example collects incoming characters into a fixed-size buffer and processes a command when a newline is received.

const size_t BUFFER_SIZE = 32; char commandBuffer[BUFFER_SIZE]; size_t commandLength = 0; void setup() { Serial.begin(115200); Serial.println("Type ON or OFF and press Enter."); } void loop() { while (Serial.available() > 0) { char incoming = Serial.read(); if (incoming == '\r') { continue; } if (incoming == '\n') { commandBuffer[commandLength] = '\0'; if (strcmp(commandBuffer, "ON") == 0) { Serial.println("Device ON command received"); } else if (strcmp(commandBuffer, "OFF") == 0) { Serial.println("Device OFF command received"); } else { Serial.println("Unknown command"); } commandLength = 0; } else if (commandLength < BUFFER_SIZE - 1) { commandBuffer[commandLength++] = incoming; } else { // Reject an overlong command and reset the buffer. commandLength = 0; Serial.println("Command too long"); } } }

How it works

  1. Serial.available() checks whether data is waiting to be read.
  2. Serial.read() reads one character.
  3. Carriage returns are ignored.
  4. A newline marks the end of a command.
  5. The program adds a null terminator to form a valid C-style string.
  6. strcmp() compares the command with "ON" and "OFF".
  7. The buffer is reset for the next command.

Select a Serial Monitor line-ending option that sends a newline, such as Newline or Both NL & CR.

This example demonstrates basic input handling. For production device-control commands, also consider timeouts, malformed input, authorization, and safe handling of buffer overflow conditions.

20. Arrays of Strings

Sometimes an application needs to store several text values.

Using an array of Arduino strings

String sensorNames[] = { "Temperature", "Humidity", "Pressure" }; void setup() { Serial.begin(115200); for (size_t i = 0; i < 3; i++) { Serial.println(sensorNames[i]); } } void loop() { }

Output:

Temperature Humidity Pressure

Using an array of C-style strings

const char* sensorNames[] = { "Temperature", "Humidity", "Pressure" };

Each element points to a string literal.

This approach can be convenient for fixed labels, but do not attempt to modify the string literals through these pointers.

Arrays of strings are useful for menu labels, device names, status messages, and lists of predefined commands.

21. Choosing Between String and C-Style Strings

Both approaches have useful applications.

FeatureArduino StringC-style strings
Ease of useGenerally easierRequires more manual handling
Length managementDynamicBuffer size must be managed
Memory behaviorMay allocate dynamicallyCan use fixed buffers
Common operationsConvenient methods and operatorsStandard functions such as strcmp()
Suitable useSimple text processing and prototypesFixed-size buffers and low-level interfaces

Which approach should you use?

For beginner projects, Arduino String is convenient and readable.

For long-running embedded systems, fixed-size buffers may provide more predictable memory usage, especially when processing repeated network requests or large amounts of incoming text.

Dynamic String allocation does not automatically make a program unsafe or unreliable. The important considerations are allocation patterns, available heap memory, input size, and the behavior of the application over time.

22. Memory Considerations

ESP32 applications have limited memory compared with desktop computers. Large arrays and text buffers should be planned carefully.

Array memory usage

For a fixed array, the approximate memory occupied by its elements is:

Array memory = Number of elements × Size of each element

For example, if a uint16_t occupies two bytes on the target platform, an array of 100 elements occupies 200 bytes for its elements.

uint16_t readings[100];

Other program data, alignment, and memory allocation may increase the total memory used by an application.

String memory usage

Strings require space for their characters and a terminating null character when represented as C-style strings.

For example:

char deviceName[16] = "ESP32";

The array reserves 16 bytes, even though the text currently contains only five characters and its null terminator.

When designing buffers:

  • Choose a suitable maximum size.
  • Keep track of the number of valid characters.
  • Reserve space for the null terminator.
  • Check input lengths before copying.
  • Avoid writing beyond array boundaries.
  • Monitor heap usage when using dynamic strings extensively.

23. Practical ESP32 Project: Sensor Reading History

This example simulates temperature readings and stores them in an array. It then calculates their average.

const size_t SAMPLE_COUNT = 5; float temperatures[SAMPLE_COUNT] = { 25.2, 25.5, 26.1, 25.8, 26.0 }; void setup() { Serial.begin(115200); float total = 0.0; for (size_t i = 0; i < SAMPLE_COUNT; i++) { Serial.print("Reading "); Serial.print(i + 1); Serial.print(": "); Serial.print(temperatures[i]); Serial.println(" C"); total += temperatures[i]; } float average = total / SAMPLE_COUNT; Serial.print("Average temperature: "); Serial.print(average); Serial.println(" C"); } void loop() { }

This example demonstrates how arrays can organize sensor measurements and how loops can process them.

In a real application, readings could come from a temperature sensor. A larger project could store timestamps alongside readings, transmit them to a dashboard, or save them to flash storage.

24. Practical ESP32 Project: Text-Based Device Control

The following example demonstrates how an Arduino String can be used to interpret a command.

String command = "STATUS"; bool deviceEnabled = false; void setup() { Serial.begin(115200); if (command == "ON") { deviceEnabled = true; } else if (command == "OFF") { deviceEnabled = false; } Serial.print("Device state: "); Serial.println(deviceEnabled ? "ON" : "OFF"); } void loop() { }

The current command is "STATUS", so neither the "ON" nor "OFF" condition changes the state. The program prints OFF.

In a real project, the command could come from a serial connection, Bluetooth interface, or authenticated web request. Validate commands before using them to control physical devices.

25. Common Mistakes

Starting an array index at 1

Incorrect:

int values[3] = {10, 20, 30}; // values[3] is outside the array.

The valid indexes are 0, 1, and 2.

Forgetting the null terminator

C-style strings need a terminating '\0' character. A character buffer that is not properly terminated cannot safely be used with functions expecting a C-style string.

Copying text into a small buffer

Always ensure that a destination array has sufficient capacity for the copied text and the null terminator.

Confusing a character with a string

char letter = 'A'; const char* word = "A";

The first stores one character. The second points to a null-terminated string.

Comparing C-style strings using ==

Use strcmp() to compare their contents.

Ignoring memory limits

Large arrays and repeatedly allocated text can consume significant memory. Choose buffer sizes based on actual application requirements.

Accessing an invalid index

Always ensure that an array index is within its valid range before accessing an element.

26. Practice Exercises

Complete these exercises to test your understanding:

  1. Create an integer array containing ten values and print each value.
  2. Calculate the sum and average of an array of sensor readings.
  3. Find the maximum and minimum values in an array.
  4. Create an array of LED GPIO pins and iterate over it.
  5. Declare a C-style string and print its length using strlen().
  6. Compare two C-style strings using strcmp().
  7. Create an Arduino String and use trim() and toUpperCase().
  8. Receive a command through the Serial Monitor and identify whether it is "ON" or "OFF".
  9. Create an array of sensor names and print each name.
  10. Build a simulated sensor monitoring program that stores readings, calculates their average, and prints a warning when a threshold is exceeded.

Summary

Arrays let you store multiple values of the same type under one name. They are useful for sensor readings, GPIO pin lists, and collections of measurements.

Strings let you work with text. C-style strings use character arrays terminated by '\0', while the Arduino String class provides convenient text manipulation.

Understanding indexing, array bounds, null termination, string comparison, and memory management will help you develop reliable ESP32 programs for sensor monitoring, communication, automation, and IoT applications.

Keep learning. Keep building. Keep growing.

© 2026 Ugenz Academy