Home / References / ESP32 Library / AsyncUDP Library
Description
The read() method is a fundamental function of the AsyncUDPPacket class that provides two distinct ways to read data from incoming UDP packets. This method is inherited from the Arduino Stream class and offers both single-byte and multi-byte reading capabilities. The method allows developers to extract data from the packet buffer sequentially, making it essential for parsing and processing UDP packet contents. As data is read using this method, the internal read index advances, ensuring that subsequent calls return the next unread bytes. The read() method works in conjunction with the available() method to implement safe and efficient data reading strategies that prevent buffer overruns and enable proper packet parsing.
Syntax and Usage
The read() method provides two overloaded implementations for different use cases:
- Single Byte Reading:
int byteValue = packet.read();– Reads and returns a single byte from the packet - Multi-Byte Reading:
size_t bytesRead = packet.read(buffer, length);– Reads multiple bytes into a provided buffer
// Example of basic usage
void onPacketReceived(AsyncUDPPacket packet) {
// Single byte reading
int singleByte = packet.read();
// Multi-byte reading
uint8_t buffer[64];
size_t bytesRead = packet.read(buffer, sizeof(buffer));
}Argument(s)
Single Byte Version: This version requires no arguments.
Multi-Byte Version: This version requires the following arguments:
- data:
uint8_t *data– Pointer to the buffer where the read data will be stored - len:
size_t len– Maximum number of bytes to read from the packet
Return Value
Single Byte Version: Returns an integer value representing the next byte in the packet. If there are no more bytes available to read, the method returns -1. The returned value is in the range of 0-255 for valid data bytes, making it easy to detect end-of-data conditions.
Multi-Byte Version: Returns a size_t value indicating the actual number of bytes that were successfully read from the packet and stored in the provided buffer. This value may be less than the requested length if fewer bytes are available in the packet. The method never reads more bytes than are available, ensuring safe buffer operations.
Example Codes
How to Use Both Examples Together
To fully test the read() method functionality, follow these comprehensive steps:
- Set up the Server: Upload Example 1 (UDP Server) to your first ESP32 and note its IP address from the Serial Monitor
- Configure the Client: In Example 2 (UDP Client), update the
SERVER_IPconstant with your server’s IP address - Deploy the Client: Upload Example 2 to a second ESP32 or compatible device
- Observe the Testing: The client will automatically send different types of data every 5 seconds:
- Text messages demonstrating character-by-character reading
- Binary data packets showing hexadecimal byte processing
- Mixed alphanumeric content for comprehensive testing
- Number sequences in ASCII format for educational purposes
- Monitor Results: Watch both Serial Monitors to observe how the
read()method:- Processes each byte sequentially from the packet buffer
- Returns -1 when no more data is available
- Advances the internal read pointer with each successful read operation
- Integrates with
available()to manage reading loops safely - Handles different data types (text, binary, mixed) consistently
This demonstration setup provides a practical understanding of how the read() method functions in real UDP communication scenarios. The examples showcase both the single-byte reading approach and demonstrate proper integration with packet management methods, making it an excellent learning resource for ESP32 UDP communication development and efficient data processing techniques. The byte-by-byte reading approach demonstrated here is particularly useful for parsing protocols, extracting specific data fields, and implementing custom packet processing logic.
Example 1: UDP Server (Receiver) – Demonstrating read() Method
This example demonstrates how to create a UDP server that receives packets and uses the read() method to extract data byte by byte, showcasing the sequential reading capabilities and proper usage patterns for packet data processing.
/*
* Author: Avant Maker
* Date: June 23, 2025
* Version: 1.0
* License: MIT
*
* Description:
* Simple demonstration of the AsyncUDP read() method for ESP32.
* This receiver code shows different ways to use the read() method
* to extract data from incoming UDP packets byte by byte.
* This is the RECEIVER/SERVER code.
*
* Setup Instructions:
* 1. Upload this code to your ESP32 (Server)
* 2. Note the IP address shown in Serial Monitor
* 3. Update the sender code with this IP address
* 4. Upload and run the sender code on another ESP32
* 5. Watch the Serial Monitor to see read() method demonstrations
*
* Code Source:
* This example code is sourced from the Comprehensive Guide
* to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
* For additional code examples and in-depth documentation related to
* the ESP32 Arduino Core Library, please visit:
*
* https://avantmaker.com/home/all-about-esp32-arduino-core-library/
*
* AvantMaker.com - Your Premier Hub for DIY, AI, IoT, and STEM Innovation
*/
#include <WiFi.h>
#include <AsyncUDP.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
AsyncUDP udp;
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println("=== AsyncUDP read() Method Demo - Receiver ===");
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected!");
Serial.print("Server IP: ");
Serial.println(WiFi.localIP());
// Start UDP listener on port 1234
if (udp.listen(1234)) {
Serial.println("UDP Server listening on port 1234");
Serial.println("Waiting for packets to demonstrate read() method...\n");
udp.onPacket([](AsyncUDPPacket packet) {
Serial.println("--- Packet Received ---");
Serial.print("Length: ");
Serial.print(packet.length());
Serial.println(" bytes");
// Demonstration 1: Basic read() usage - single byte reading
Serial.println("\n1. Reading bytes one by one using read():");
int byteCount = 0;
while (packet.available() > 0) {
int byteValue = packet.read(); // Read single byte
byteCount++;
Serial.print("Byte ");
Serial.print(byteCount);
Serial.print(": ");
Serial.print(byteValue);
Serial.print(" (0x");
Serial.print(byteValue, HEX);
Serial.print(")");
// Show as character if printable
if (byteValue >= 32 && byteValue <= 126) {
Serial.print(" '");
Serial.print((char)byteValue);
Serial.print("'");
}
Serial.print(" - Remaining: ");
Serial.println(packet.available());
}
Serial.print("Total bytes read: ");
Serial.println(byteCount);
Serial.println("------------------------\n");
});
} else {
Serial.println("Failed to start UDP server!");
}
}
void loop() {
delay(1000);
}Example 2: UDP Client (Sender) – Testing Companion Code
This companion example demonstrates how to send various types of UDP data to test the read() method functionality. It acts as a UDP client that sends different data patterns to help demonstrate how the read() method processes various packet contents on the receiving ESP32.
/*
* Author: Avant Maker
* Date: June 23, 2025
* Version: 1.0
* License: MIT
*
* Description:
* Simple sender code to test the AsyncUDP read() method demonstration.
* This client sends various types of data packets to help demonstrate
* how the read() method works on the receiver side.
* This is the SENDER/CLIENT code.
*
* Setup Instructions:
* 1. First run the receiver code and note its IP address
* 2. Update SERVER_IP below with the receiver's IP address
* 3. Upload this code to another ESP32 (Client)
* 4. Watch both Serial Monitors to see the read() method in action
*
* Code Source:
* This example code is sourced from the Comprehensive Guide
* to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
* For additional code examples and in-depth documentation related to
* the ESP32 Arduino Core Library, please visit:
*
* https://avantmaker.com/home/all-about-esp32-arduino-core-library/
*
* AvantMaker.com - Your Premier Hub for DIY, AI, IoT, and STEM Innovation
*/
#include <WiFi.h>
#include <AsyncUDP.h>
const char* ssid = "your_SSID"; // Replace with your Wi-Fi SSID
const char* password = "your_PASSWORD"; // Replace with your Wi-Fi password
// Update this with your receiver ESP32's IP address
const char* SERVER_IP = "192.168.0.123"; // CHANGE THIS!
const int SERVER_PORT = 1234;
AsyncUDP udp;
IPAddress serverIP;
int packetCounter = 0;
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println("=== AsyncUDP read() Method Demo - Sender ===");
// Convert IP string to IPAddress
serverIP.fromString(SERVER_IP);
Serial.print("Target server: ");
Serial.println(serverIP);
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected!");
Serial.print("Client IP: ");
Serial.println(WiFi.localIP());
Serial.println("Sending test packets every 5 seconds...\n");
}
void loop() {
packetCounter++;
Serial.print("Sending packet #");
Serial.println(packetCounter);
// Send different types of data to test read() method
switch (packetCounter % 4) {
case 1:
sendTextData();
break;
case 2:
sendBinaryData();
break;
case 3:
sendMixedData();
break;
case 0:
sendNumberSequence();
break;
}
delay(5000); // Wait 5 seconds between packets
}
void sendTextData() {
String message = "Hello ESP32!";
Serial.print("Sending text: \"");
Serial.print(message);
Serial.println("\"");
size_t sent = udp.writeTo((uint8_t*)message.c_str(), message.length(), serverIP, SERVER_PORT);
Serial.print("Bytes sent: ");
Serial.println(sent);
Serial.println();
}
void sendBinaryData() {
uint8_t binaryData[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0xFF, 0xAA, 0x55};
Serial.print("Sending binary data: ");
for (int i = 0; i < sizeof(binaryData); i++) {
Serial.print("0x");
if (binaryData[i] < 16) Serial.print("0");
Serial.print(binaryData[i], HEX);
Serial.print(" ");
}
Serial.println();
size_t sent = udp.writeTo(binaryData, sizeof(binaryData), serverIP, SERVER_PORT);
Serial.print("Bytes sent: ");
Serial.println(sent);
Serial.println();
}
void sendMixedData() {
String message = "ABC123!@#";
Serial.print("Sending mixed data: \"");
Serial.print(message);
Serial.println("\"");
size_t sent = udp.writeTo((uint8_t*)message.c_str(), message.length(), serverIP, SERVER_PORT);
Serial.print("Bytes sent: ");
Serial.println(sent);
Serial.println();
}
void sendNumberSequence() {
uint8_t numbers[] = {48, 49, 50, 51, 52}; // ASCII for "01234"
Serial.print("Sending number sequence: ");
for (int i = 0; i < sizeof(numbers); i++) {
Serial.print(numbers[i]);
Serial.print("(");
Serial.print((char)numbers[i]);
Serial.print(") ");
}
Serial.println();
size_t sent = udp.writeTo(numbers, sizeof(numbers), serverIP, SERVER_PORT);
Serial.print("Bytes sent: ");
Serial.println(sent);
Serial.println();
}ESP32 Library Index
- ESP32 WiFi Library
- ESP32 WiFiClient Library
- ESP32 HTTPClient Library
- ESP32 WiFiClientSecure Library
- ESP32 WebServer Library
- ESP32 AsyncUDP Librarry
- Connection Management
- Data Transimission
- Broadcast Multicast
- Network Information
- Which ESP32 Boards are Recommended for Learners
- How to Copy Codes from AvantMaker.com
- What is SPIFFS and how to upload files to it?
- What is LIttleFS and how to upload files to it?
Ready to experiment and explore more about ESP32? Visit our website’s All About ESP32 Resources Hub, packed with tutorials, guides, and tools to inspire your maker journey. Experiment, explore, and elevate your skills with everything you need to master this powerful microcontroller platform!