Ugenz Academy/IoT Tutorial

Serial Communication And Debugging

15 min read2,992 words

Reading progress

Keep learning

Serial Communication and Debugging in ESP32

Serial communication is one of the most useful techniques for developing, testing, and troubleshooting ESP32 projects. It allows your microcontroller to exchange data with a computer, another microcontroller, or a compatible serial device.

Debugging is the process of finding and fixing problems in a program or hardware setup. By printing sensor values, monitoring program states, receiving commands, and inspecting errors, you can understand what your ESP32 is doing while it runs.

In this lesson, you will learn Serial Monitor basics, baud rates, serial input and output, UART communication, debugging techniques, command processing, and practical ESP32 projects.

1. What Is Serial Communication?

Serial communication transfers data sequentially, one bit at a time, over a communication channel.

It is widely used in embedded systems because it provides a straightforward way to exchange information between devices.

Examples include:

  • Sending debugging messages from an ESP32 to a computer.
  • Receiving commands through Serial Monitor.
  • Communicating with GPS modules.
  • Reading data from UART sensors.
  • Exchanging messages between two microcontrollers.
  • Connecting to compatible serial adapters and industrial devices.

A simple example is printing a sensor reading to Serial Monitor so you can observe it while the ESP32 is running.

#include <Arduino.h> void setup() { Serial.begin(115200); Serial.println("ESP32 started"); } void loop() { int sensorValue = analogRead(34); Serial.print("Sensor value: "); Serial.println(sensorValue); delay(1000); }

This example assumes GPIO 34 is available as an analog input on a classic ESP32. Check your specific board's pinout.

2. What Is Serial Monitor?

Serial Monitor is a tool in the Arduino IDE that displays data sent from the ESP32 and allows you to send text back to the board.

It is useful for:

  • Checking whether a program has started.
  • Displaying sensor values.
  • Observing button states.
  • Inspecting network connection status.
  • Testing commands.
  • Finding logic errors.

Opening Serial Monitor

In Arduino IDE:

  1. Connect your ESP32 to the computer with a suitable USB cable.
  2. Select the correct ESP32 board.
  3. Select the correct serial port.
  4. Upload your sketch.
  5. Open Serial Monitor.
  6. Set the baud rate to match your program.

For example, if your program contains:

Serial.begin(115200);

select 115200 in Serial Monitor.

The connection method depends on your development board. Some ESP32 boards use a USB-to-UART bridge, while others support native USB serial.

3. Understanding Baud Rate

The baud rate describes the signaling rate of a serial connection. In conventional UART configurations, it is commonly expressed in bits per second.

Common rates include:

  • 9600
  • 19200
  • 38400
  • 57600
  • 115200

For example:

Serial.begin(115200);

This initializes the primary Arduino serial interface with a rate of 115200 for conventional UART communication.

Why Must the Baud Rates Match?

The sender and receiver need compatible serial settings to interpret the transmitted data correctly.

If your program uses:

Serial.begin(115200);

but Serial Monitor is set to 9600, the displayed output may appear unreadable or incorrect when the connection uses a conventional UART baud rate.

For a USB CDC serial connection, the baud setting may not control the physical USB transmission rate in the same way, depending on the board and configuration.

4. Serial.begin()

The Serial.begin() function initializes the primary serial interface.

Syntax

Serial.begin(baudRate);

Example:

#include <Arduino.h> void setup() { Serial.begin(115200); Serial.println("Serial communication initialized"); } void loop() { }

Output

Serial communication initialized

Use Serial.begin() before relying on the serial interface for debugging output.

5. Serial.print() and Serial.println()

These functions send readable text and values through the serial interface.

Serial.print()

Prints data without automatically adding a new line.

Serial.print("Temperature: "); Serial.print(28.5);

Output:

Temperature: 28.5

Serial.println()

Prints data and then adds a line ending.

Serial.println("ESP32 is running");

Output:

ESP32 is running

Printing Multiple Values

#include <Arduino.h> void setup() { Serial.begin(115200); int temperature = 28; int humidity = 65; Serial.print("Temperature: "); Serial.print(temperature); Serial.println(" C"); Serial.print("Humidity: "); Serial.print(humidity); Serial.println("%"); } void loop() { }

Output:

Temperature: 28 C Humidity: 65%

For floating-point values, you can specify the number of decimal places:

float voltage = 3.14159f; Serial.println(voltage, 2);

Output:

3.14

6. Debugging with Serial Output

Serial output is a simple way to understand what is happening inside a program.

For example, if an LED is not turning on, print messages before and after the GPIO operation.

#include <Arduino.h> const int LED_PIN = 2; void setup() { Serial.begin(115200); Serial.println("Starting ESP32..."); pinMode(LED_PIN, OUTPUT); Serial.println("LED pin configured"); } void loop() { Serial.println("Turning LED ON"); digitalWrite(LED_PIN, HIGH); delay(1000); Serial.println("Turning LED OFF"); digitalWrite(LED_PIN, LOW); delay(1000); }

What Can You Learn?

If the first message appears but the next message does not, the problem may be occurring between those operations.

If all messages appear but the LED does not respond, investigate the GPIO pin, wiring, LED polarity, resistor, and board pinout.

Important: A debug message confirms that program execution reached a particular point. It does not prove that the connected hardware performed the expected action.

7. Using Serial Monitor to Receive Input

Serial communication is not limited to sending information. The ESP32 can also receive data from your computer.

The main functions are:

FunctionPurpose
Serial.available()Returns the number of bytes available to read
Serial.read()Reads one byte
Serial.peek()Looks at the next byte without removing it
Serial.readString()Reads data into an Arduino String, subject to timeout behavior
Serial.readStringUntil()Reads until a specified terminator or timeout

For robust embedded programs, consider fixed-size buffers and explicit parsing instead of allocating strings repeatedly.

Example: Read One Character

#include <Arduino.h> void setup() { Serial.begin(115200); Serial.println("Type a character:"); } void loop() { if (Serial.available() > 0) { char received = Serial.read(); Serial.print("Received character: "); Serial.println(received); } }

Type a character into Serial Monitor and send it.

The ESP32 reads one byte and displays it. If Serial Monitor sends a line ending, that ending may be received as an additional character.

8. Reading a Complete Line from Serial Monitor

Sometimes you want to receive a complete command rather than one character at a time.

For example, the user might type:

ON

or:

OFF

The following example uses a fixed-size character buffer and processes input when a newline arrives.

#include <Arduino.h> const size_t BUFFER_SIZE = 32; char inputBuffer[BUFFER_SIZE]; size_t inputLength = 0; void processCommand(const char* command) { Serial.print("Received command: "); Serial.println(command); if (strcmp(command, "ON") == 0) { Serial.println("Action: Turn ON"); } else if (strcmp(command, "OFF") == 0) { Serial.println("Action: Turn OFF"); } else { Serial.println("Unknown command"); } } void setup() { Serial.begin(115200); Serial.println("Enter ON or OFF"); } void loop() { while (Serial.available() > 0) { char incoming = Serial.read(); if (incoming == '\r') { continue; } if (incoming == '\n') { inputBuffer[inputLength] = '\0'; if (inputLength > 0) { processCommand(inputBuffer); } inputLength = 0; } else if (inputLength < BUFFER_SIZE - 1) { inputBuffer[inputLength++] = incoming; } else { Serial.println("Input too long; command discarded"); inputLength = 0; // Ignore the remainder of this line. while (Serial.available() > 0) { char remaining = Serial.read(); if (remaining == '\n') { break; } } } } }

How It Works

  1. Incoming bytes are read from Serial.
  2. Characters are stored in a fixed-size buffer.
  3. A newline indicates the end of a command.
  4. The buffer is terminated with '\0' to create a valid C-style string.
  5. strcmp() compares the command with the expected text.
  6. Unknown or oversized commands are handled without writing beyond the buffer.

This is a simple line parser. Production command parsers may need stronger recovery logic, command validation, and input length limits.

9. UART Communication on ESP32

UART stands for Universal Asynchronous Receiver/Transmitter.

It is a common serial communication interface used to exchange data between two devices without a shared clock signal.

A UART connection commonly uses:

  • TX: Transmit data.
  • RX: Receive data.
  • GND: Shared signal reference, when required by the circuit.

For a typical two-device UART connection:

  • Device A TX connects to Device B RX.
  • Device A RX connects to Device B TX.
  • The devices share GND when required.

The two devices must use compatible baud rates and serial formats.

ESP32 UART Interfaces

Depending on the chip, the ESP32 provides multiple UART peripherals. Arduino-ESP32 exposes hardware serial objects such as Serial, Serial1, and, on supported targets, Serial2.

The exact peripheral count and pin routing depend on the chip and board.

Avoid connecting external devices to pins used by USB, boot configuration, or onboard hardware without checking the board documentation.

10. Communicating with a UART Device

The following example demonstrates how to initialize an additional hardware UART.

#include <Arduino.h> HardwareSerial SensorSerial(2); const int UART_RX_PIN = 16; const int UART_TX_PIN = 17; void setup() { Serial.begin(115200); SensorSerial.begin( 9600, SERIAL_8N1, UART_RX_PIN, UART_TX_PIN ); Serial.println("UART interface initialized"); } void loop() { while (SensorSerial.available() > 0) { int received = SensorSerial.read(); Serial.print("Received byte: 0x"); if (received < 16) { Serial.print("0"); } Serial.println(received, HEX); } }

Understanding HardwareSerial.begin()

The parameters are:

SensorSerial.begin( baudRate, serialConfig, rxPin, txPin );
  • baudRate: Communication rate.
  • serialConfig: Data format, such as SERIAL_8N1.
  • rxPin: GPIO used for reception.
  • txPin: GPIO used for transmission.

SERIAL_8N1 means eight data bits, no parity, and one stop bit.

The pin numbers in this example are common choices on many classic ESP32 boards, not universal assignments. Confirm that the pins are available on your board.

This example reads bytes but does not decode any specific sensor protocol. A real sensor may require commands, checksums, framing, or packet parsing.

11. Sending Data over UART

You can also transmit data to another device through a hardware UART.

#include <Arduino.h> HardwareSerial DeviceSerial(2); const int UART_RX_PIN = 16; const int UART_TX_PIN = 17; void setup() { Serial.begin(115200); DeviceSerial.begin( 9600, SERIAL_8N1, UART_RX_PIN, UART_TX_PIN ); } void loop() { DeviceSerial.println("HELLO"); Serial.println("UART message sent"); delay(1000); }

This sends the text HELLO followed by a line ending once per second.

The receiving device must use compatible UART settings and understand the message format.

Electrical safety: Check voltage levels before connecting UART devices. ESP32 GPIO uses 3.3 V logic and should not be assumed to tolerate 5 V signals. RS-232 and RS-485 interfaces require appropriate transceivers rather than direct GPIO connections.

12. Debugging Sensor Readings

When working with sensors, print both raw and processed values to distinguish hardware problems from calculation problems.

#include <Arduino.h> const int SENSOR_PIN = 34; void setup() { Serial.begin(115200); } void loop() { int rawValue = analogRead(SENSOR_PIN); float approximatePercentage = (rawValue / 4095.0f) * 100.0f; Serial.print("Raw ADC: "); Serial.print(rawValue); Serial.print(" | Approximate percentage: "); Serial.print(approximatePercentage, 1); Serial.println("%"); delay(1000); }

The percentage calculation assumes a 12-bit ADC reading with a range of 0–4095. It is only a normalized percentage of that numerical range, not necessarily a percentage of the physical quantity measured by your sensor.

To diagnose an unexpected reading:

  1. Check the sensor's power supply.
  2. Check the ground and signal connections.
  3. Confirm the pin supports the required input mode.
  4. Observe the raw reading before applying calculations.
  5. Check the ADC configuration and input voltage.
  6. Compare the reading against a known condition.

13. Using Debug Levels

Large programs can generate too much debug output. Debug levels help you distinguish important errors from routine information.

A simple approach uses a preprocessor definition.

#include <Arduino.h> #define DEBUG_ENABLED 1 #if DEBUG_ENABLED #define DEBUG_PRINT(x) Serial.print(x) #define DEBUG_PRINTLN(x) Serial.println(x) #else #define DEBUG_PRINT(x) #define DEBUG_PRINTLN(x) #endif void setup() { Serial.begin(115200); DEBUG_PRINTLN("Application started"); } void loop() { int sensorValue = 100; DEBUG_PRINT("Sensor value: "); DEBUG_PRINTLN(sensorValue); delay(1000); }

Set DEBUG_ENABLED to 0 to disable these debug messages at compile time.

This simple macro setup is suitable for basic logging. Larger projects can use a logging system with levels such as DEBUG, INFO, WARNING, and ERROR.

Avoid printing passwords, private keys, tokens, or other sensitive information.

14. Measuring Execution Time

Serial debugging can help identify slow operations by measuring elapsed time.

The micros() function returns an elapsed-time counter in microseconds.

#include <Arduino.h> void setup() { Serial.begin(115200); } void loop() { unsigned long startTime = micros(); // Operation being measured volatile unsigned long total = 0; for (int i = 0; i < 1000; i++) { total += i; } unsigned long elapsedTime = micros() - startTime; Serial.print("Elapsed time: "); Serial.print(elapsedTime); Serial.println(" microseconds"); delay(1000); }

The volatile variable helps ensure that the calculation remains observable to the compiler, although compiler behavior and optimization still influence benchmark results.

Timing measurements include some overhead and should not be treated as exact performance guarantees. For accurate benchmarking, control the test conditions and consider compiler optimization and peripheral timing.

15. Debugging Wi-Fi Connections

Serial output is useful for tracking network connection progress.

#include <Arduino.h> #include <WiFi.h> const char* ssid = "YOUR_WIFI_NAME"; const char* password = "YOUR_WIFI_PASSWORD"; void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); Serial.println("Connecting to Wi-Fi..."); } void loop() { static bool reportedConnected = false; if (WiFi.status() == WL_CONNECTED) { if (!reportedConnected) { Serial.println("Wi-Fi connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); reportedConnected = true; } } else { if (reportedConnected) { Serial.println("Wi-Fi disconnected"); reportedConnected = false; } } delay(100); }

This example reports connection and disconnection transitions. It does not implement a complete recovery strategy.

If the connection fails, verify the credentials, access point compatibility, signal strength, and whether your ESP32 supports the selected network configuration.

Keep credentials private and use secure storage appropriate to your application.

16. Common Serial Communication Problems

Problem 1: No Output Appears

Check:

  • Whether the correct serial port is selected.
  • Whether the board is powered and running.
  • Whether the USB cable supports data.
  • Whether the program calls Serial.begin().
  • Whether the selected serial interface matches your board's USB configuration.
  • Whether the baud setting matches the conventional UART configuration.

Some boards require a reset or boot action after opening the serial connection.

Problem 2: Unreadable Output

For a conventional UART connection, check the baud rate and serial format.

For native USB CDC, the baud setting may not represent the physical USB transfer rate, so also check the selected port and USB configuration.

Problem 3: Serial Input Is Incomplete

Check:

  • Whether your program reads all available bytes.
  • Whether Serial Monitor sends a newline or carriage return.
  • Whether your input buffer is large enough.
  • Whether the program correctly handles long commands.
  • Whether input processing blocks other work.

Problem 4: UART Device Sends No Data

Check:

  • TX and RX wiring.
  • Shared ground where required.
  • Baud rate and serial format.
  • Voltage-level compatibility.
  • Correct GPIO assignments.
  • Whether the external device requires initialization or a request command.

Problem 5: Garbled UART Data

Possible causes include mismatched baud rates, incorrect data format, electrical noise, unsuitable voltage levels, or incorrect interpretation of the device's protocol.

Problem 6: Debug Output Changes Program Behavior

Serial output consumes time and can alter timing-sensitive behavior. Excessive logging can also affect buffer usage and task scheduling.

For time-sensitive operations, reduce logging, buffer messages where appropriate, or use a more suitable debugging method.

17. Best Practices for Serial Communication and Debugging

  • Start with a consistent baud rate such as 115200 for ordinary debugging.
  • Print startup messages to confirm the program has reached setup().
  • Label values so output is easy to interpret.
  • Print raw sensor readings before converting them.
  • Use debug levels to control output volume.
  • Avoid logging secrets or sensitive data.
  • Keep UART framing and message formats documented.
  • Use bounded input buffers for commands.
  • Handle invalid and oversized commands safely.
  • Avoid long blocking operations in time-sensitive loops.
  • Do not print from interrupt handlers.
  • Verify wiring, voltage levels, and board pin assignments.
  • Use a logic analyzer or oscilloscope when software logs cannot explain a timing or signal problem.
  • Check the documentation for the exact ESP32 chip and Arduino-ESP32 core version.

18. Practice Exercises

Beginner

  1. Print Hello ESP32 to Serial Monitor.
  2. Display an incrementing counter once per second.
  3. Read an analog sensor and print its raw value.
  4. Receive a character and display it.
  5. Create a program that prints whether a button is pressed or released.

Intermediate

  1. Build a command interface that accepts ON, OFF, and STATUS.
  2. Read bytes from an external UART device.
  3. Send a message from one ESP32 to another using UART.
  4. Add debug macros that can be disabled at compile time.
  5. Measure the elapsed time of a sensor-reading function.

Advanced

  1. Implement a bounded serial command parser with input validation.
  2. Decode a documented UART sensor packet and validate its checksum.
  3. Create a logging system with INFO, WARNING, and ERROR levels.
  4. Diagnose a serial communication failure using wiring checks and a logic analyzer.
  5. Build a Wi-Fi-connected sensor monitor that logs connection changes and sensor errors.

Summary

Serial communication and debugging are essential skills for reliable ESP32 development.

In this lesson, you learned:

  • How serial communication works.
  • How to configure Serial Monitor and baud rates.
  • How to use Serial.begin(), Serial.print(), and Serial.println().
  • How to receive single characters and complete commands.
  • How to configure hardware UART communication.
  • How to debug sensor readings and Wi-Fi connections.
  • How to use debug levels and measure execution time.
  • How to identify common serial communication problems.
  • How to apply safe and maintainable debugging practices.

Key takeaway: Effective debugging makes ESP32 development faster and more reliable. Use clear serial messages, validate incoming data, understand your hardware's communication interfaces, and investigate both software logic and physical wiring when something does not work.

Keep learning. Keep building. Keep growing.

© 2026 Ugenz Academy