Home / References / ESP32 Library / AsyncUDP Library
Description
The data() method is a fundamental function of the AsyncUDPPacket class that provides direct access to the raw packet data received via UDP communication. This method returns a pointer to the beginning of the packet’s payload, allowing developers to read and process the actual data content that was transmitted over the network. The method is essential for accessing the received UDP packet data in its raw byte format, enabling flexible data processing and parsing operations.
This page is part of the Comprehensive Guide to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
Syntax and Usage
The data() method can be used in the following way:
Basic Usage: uint8_t* dataPtr = packet.data();
– Retrieves a pointer to the packet data buffer without any arguments
// Example of basic usage
void onPacketReceived(AsyncUDPPacket packet) {
uint8_t* packetData = packet.data();
// Process the raw packet data
}For practical applications and examples of this method, please consult the “Example Code” section on this page. This section provides comprehensive guidance to help you better understand and apply the method effectively.
Argument(s)
This method does not require any arguments.
Return Value
The data() method returns a pointer of type uint8_t* that points to the beginning of the received packet’s data buffer. This pointer provides direct access to the raw bytes of the UDP packet payload. The returned pointer remains valid for the lifetime of the AsyncUDPPacket object and should be used in conjunction with the length() method to determine the size of the available data.
Example Codes
Example 1: UDP Server (Receiver) – Testing data() Method
This example demonstrates how to create a UDP server that receives packets and uses the data() method to access and analyze the received data.
/*
* Author: Avant Maker
* Date: June 23, 2025
* Version: 1.0
* License: MIT
*
* Description:
* This example demonstrates how to use the data() method to access
* raw packet data from incoming UDP packets and process the received
* information byte by byte. This is the SERVER/RECEIVER code.
*
* How to use this example (Server Setup):
* 1. Upload this code to your ESP32 (Server)
* 2. Connect the ESP32 to your WiFi network
* 3. Note the IP address displayed in Serial Monitor
* 4. Use the companion UDP Client code below to send test data
* 5. Monitor the Serial output to see the received data analysis
*
* Testing with the companion client:
* - Run this server code first
* - Then run the UDP Client Sender code (Example 2 below) on another device
* - The client will automatically send various types of test data
* - Observe how the data() method processes different packet types
*
* 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 destination for all things
* DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated
* to empowering makers, learners, and enthusiasts with
* the resources they need to bring their innovative ideas to life.
*/
#include <WiFi.h>
#include <AsyncUDP.h>
const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";
AsyncUDP udp;
void setup() {
Serial.begin(115200);
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("WiFi connected!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Start UDP server on port 1234
if (udp.listen(1234)) {
Serial.println("UDP server started on port 1234");
Serial.println("Waiting for UDP packets...");
udp.onPacket([](AsyncUDPPacket packet) {
// Get pointer to packet data using data() method
uint8_t* packetData = packet.data();
size_t dataLength = packet.length();
Serial.print("Received packet with ");
Serial.print(dataLength);
Serial.println(" bytes:");
// Process each byte of the packet data
Serial.print("Raw data: ");
for (size_t i = 0; i < dataLength; i++) {
Serial.print("0x");
Serial.print(packetData[i], HEX);
Serial.print(" ");
}
Serial.println();
// Convert to string if it contains printable characters
Serial.print("As string: ");
for (size_t i = 0; i < dataLength; i++) {
if (packetData[i] >= 32 && packetData[i] <= 126) {
Serial.print((char)packetData[i]);
} else {
Serial.print(".");
}
}
Serial.println();
Serial.print("From: ");
Serial.print(packet.remoteIP());
Serial.print(":");
Serial.println(packet.remotePort());
Serial.println("---");
});
} else {
Serial.println("Failed to start UDP server!");
}
}
void loop() {
// Main loop - UDP handling is done asynchronously
delay(1000);
}Example 2: UDP Client (Sender) – Testing Companion Code
This companion example acts as a UDP client that sends various types of data to test the data() method functionality on the receiving ESP32. Use this code to automatically generate test packets for the server above.
/*
* Author: Avant Maker
* Date: June 23, 2025
* Version: 1.1 (Fixed)
* License: MIT
*
* Description:
* This companion example demonstrates how to send UDP data to an ESP32
* running the data() method example. It acts as a UDP client that sends
* various types of data packets to test the data() method functionality
* on the receiving ESP32. This is the CLIENT/SENDER code.
*
* FIXED VERSION - Corrected UDP sending issues
*
* How to use this example (Client Setup):
* 1. First, upload and run Example 1 (UDP Server) on your ESP32 server
* 2. Note the IP address displayed by the server in Serial Monitor
* 3. Update the SERVER_IP constant below with the server's IP address
* 4. Upload this code to another ESP32 or compatible device (Client)
* 5. Open Serial Monitor on both devices to see data transmission
* 6. Observe the server's Serial Monitor to see data() method processing
*
* Complete testing procedure:
* - Run the UDP Server (Example 1) first and note its IP address
* - Update SERVER_IP in this client code with the server's IP
* - Run this client code on a second device
* - The client will automatically send different types of test data every 5 seconds
* - Watch both Serial Monitors to see the complete data transmission and processing
*
* 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 destination for all things
* DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated
* to empowering makers, learners, and enthusiasts with
* the resources they need to bring their innovative ideas to life.
*/
#include
#include
// WiFi credentials
const char* ssid = "your_SSID"; // Replace with your Wi-Fi SSID
const char* password = "your_PASSWORD"; // Replace with your Wi-Fi password
// Server configuration (update with your server ESP32's IP address)
const char* SERVER_IP = "192.168.0.123"; // Change this to your server's IP
const int SERVER_PORT = 1234;
AsyncUDP udp;
IPAddress serverIP;
unsigned long lastSendTime = 0;
const unsigned long sendInterval = 5000; // Send every 5 seconds
int messageCounter = 0;
void setup() {
Serial.begin(115200);
Serial.println("UDP Client Sender Starting...");
// Convert server IP string to IPAddress object
serverIP.fromString(SERVER_IP);
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("WiFi connected!");
Serial.print("Client IP address: ");
Serial.println(WiFi.localIP());
Serial.print("Will send data to server: ");
Serial.print(SERVER_IP);
Serial.print(":");
Serial.println(SERVER_PORT);
Serial.println("UDP client ready to send data!");
Serial.println("---");
}
void loop() {
// Send different types of data every 5 seconds
if (millis() - lastSendTime >= sendInterval) {
sendTestData();
lastSendTime = millis();
messageCounter++;
}
delay(100);
}
void sendTestData() {
String testMessages[] = {
"Hello from UDP Client!",
"Testing data() method",
"Message #" + String(messageCounter),
"Special chars: !@#$%^&*()",
"Numbers: 12345",
"ESP32 UDP Test"
};
// Send text message
int msgIndex = messageCounter % 6;
String message = testMessages[msgIndex];
Serial.print("Sending text message: '");
Serial.print(message);
Serial.println("'");
// Use writeTo() method to send data to specific IP and port
size_t bytesSent = udp.writeTo((uint8_t*)message.c_str(), message.length(), serverIP, SERVER_PORT);
Serial.print("Bytes sent: ");
Serial.println(bytesSent);
delay(1000);
// Send binary data
Serial.println("Sending binary data packet");
uint8_t binaryData[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0xFF, 0xAB, 0xCD};
bytesSent = udp.writeTo(binaryData, sizeof(binaryData), serverIP, SERVER_PORT);
Serial.print("Binary bytes sent: ");
Serial.println(bytesSent);
delay(1000);
// Send mixed data (text + binary)
Serial.println("Sending mixed data packet");
uint8_t mixedData[] = {'H', 'i', '!', 0x00, 0x01, 0x02, 'E', 'n', 'd'};
bytesSent = udp.writeTo(mixedData, sizeof(mixedData), serverIP, SERVER_PORT);
Serial.print("Mixed data bytes sent: ");
Serial.println(bytesSent);
delay(1000);
// Send JSON-like data
String jsonData = "{\"sensor\":\"temp\",\"value\":25.4,\"unit\":\"C\"}";
Serial.print("Sending JSON data: ");
Serial.println(jsonData);
bytesSent = udp.writeTo((uint8_t*)jsonData.c_str(), jsonData.length(), serverIP, SERVER_PORT);
Serial.print("JSON bytes sent: ");
Serial.println(bytesSent);
Serial.println("--- All test packets sent ---");
Serial.println();
}How to Use Both Examples Together
To fully test the data() method functionality, follow these 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 various types of data every 5 seconds:
- Text messages with different content
- Binary data packets
- Mixed text and binary data
- JSON-formatted data
- Empty packets for edge case testing
- Monitor Results: Watch both Serial Monitors to see how the
data()method processes different packet types, displaying both hexadecimal and string representations
This comprehensive testing setup demonstrates the versatility and power of the data() method in handling various UDP packet formats, making it an excellent learning tool for ESP32 UDP communication development.
For more ESP32 development resources and tutorials, visit the All About ESP32 Resources Hub on AvantMaker.com
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!