ESP32 AsyncUDP Library – available()

Home / References / ESP32 Library / AsyncUDP Library

Description

The available() method is a fundamental function of the AsyncUDPPacket class that returns the number of bytes available for reading from the current UDP packet. This method is essential for determining how much data remains to be read from the packet buffer before processing or parsing the packet content. The method is inherited from the Arduino Stream class and provides a standard way to check the remaining unread data in the packet, allowing developers to implement efficient data reading strategies and avoid buffer overruns.

Syntax and Usage

The available() method can be used in the following way:

  • Basic Usage: int bytesAvailable = packet.available(); – Returns the number of bytes available for reading without any arguments
// Example of basic usage
void onPacketReceived(AsyncUDPPacket packet) {
    int remainingBytes = packet.available();
    // Process based on available data
}

Argument(s)

This method does not require any arguments.

Return Value

The available() method returns an integer value representing the number of bytes that are still available to be read from the UDP packet buffer. The return value decreases as data is read from the packet using methods like read(). When the method returns 0, it indicates that all data in the packet has been read. The method will never return a negative value, making it safe to use in loop conditions and buffer management operations.

Example Codes

How to Use Both Examples Together

To fully test the available() method functionality, follow these steps:

  1. Set up the Server: Upload Example 1 (UDP Server) to your first ESP32 and note its IP address from the Serial Monitor
  2. Configure the Client: In Example 2 (UDP Client), update the SERVER_IP constant with your server’s IP address
  3. Deploy the Client: Upload Example 2 to a second ESP32 or compatible device
  4. Observe the Testing: The client will automatically send various types of data every 5 seconds:
    • Text messages with different content and lengths
    • Binary data packets of various sizes
    • Mixed text and binary data combinations
    • JSON-formatted data structures
    • Different packet sizes for comprehensive testing
  5. Monitor Results: Watch both Serial Monitors to see how the available() method tracks the remaining bytes as data is read sequentially, demonstrating its utility in managing packet reading operations

This comprehensive testing setup demonstrates the practical utility of the available() method in managing UDP packet reading operations, making it an excellent learning tool for ESP32 UDP communication development and efficient data processing techniques.

Example 1: UDP Server (Receiver) – Testing available() Method

This example demonstrates how to create a UDP server that receives packets and uses the available() method to monitor and control the reading process of incoming data.

/*
* Author: Avant Maker
* Date: June 23, 2025
* Version: 1.1 (Fixed)
* License: MIT
* 
* Description: 
* This example demonstrates how to use the available() method to monitor
* the number of bytes available for reading from incoming UDP packets
* and implement efficient data reading strategies. This is the SERVER/RECEIVER code.
* FIXED VERSION - Corrected packet handling and reading issues.
*
* 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 to send test data
* 5. Monitor the Serial output to see the available() method tracking bytes
*
* 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_SSID";          // Replace with your Wi-Fi SSID
const char* password = "your_PASSWORD";  // Replace with your Wi-Fi password

AsyncUDP udp;
unsigned long packetCount = 0;

void setup() {
    Serial.begin(115200);
    delay(1000);
    
    Serial.println("=== UDP Server Starting ===");
    
    // Connect to WiFi
    WiFi.begin(ssid, password);
    Serial.print("Connecting to WiFi");
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println();
    
    Serial.println("WiFi connected successfully!");
    Serial.print("Server IP address: ");
    Serial.println(WiFi.localIP());
    Serial.print("Server MAC address: ");
    Serial.println(WiFi.macAddress());
    
    // Start UDP server on port 1234
    if (udp.listen(1234)) {
        Serial.println("UDP server started successfully on port 1234");
        Serial.println("Waiting for UDP packets...");
        Serial.println("================================");
        
        udp.onPacket([](AsyncUDPPacket packet) {
            packetCount++;
            
            Serial.print("\n>>> PACKET #");
            Serial.print(packetCount);
            Serial.println(" RECEIVED <<<");
            
            // Get packet information
            size_t totalLength = packet.length();
            Serial.print("Total packet length: ");
            Serial.print(totalLength);
            Serial.println(" bytes");
            
            Serial.print("From: ");
            Serial.print(packet.remoteIP());
            Serial.print(":");
            Serial.println(packet.remotePort());
            
            // Handle empty packets
            if (totalLength == 0) {
                Serial.println(">>> Empty packet received (0 bytes)");
                Serial.print("Available bytes: ");
                Serial.println(packet.available());
                Serial.println("---");
                return;
            }
            
            // Demonstrate available() method usage
            Serial.print("Initial bytes available: ");
            Serial.println(packet.available());
            
            // Method 1: Read data byte by byte and monitor available() count
            Serial.println("\n--- Reading byte by byte ---");
            int byteCount = 0;
            String byteByByteData = "";
            
            // Create a copy of packet data for byte-by-byte reading
            uint8_t* packetData = packet.data();
            size_t remainingBytes = totalLength;
            
            for (size_t i = 0; i < totalLength && i < 50; i++) { // Limit output for readability
                uint8_t currentByte = packetData[i];
                byteCount++;
                remainingBytes--;
                
                Serial.print("Byte ");
                Serial.print(byteCount);
                Serial.print(": 0x");
                if (currentByte < 16) Serial.print("0");
                Serial.print(currentByte, HEX);
                Serial.print(" (");
                if (currentByte >= 32 && currentByte <= 126) {
                    Serial.print((char)currentByte);
                    byteByByteData += (char)currentByte;
                } else {
                    Serial.print(".");
                    byteByByteData += ".";
                }
                Serial.print(") - Remaining: ");
                Serial.println(remainingBytes);
                
                if (i >= 49 && totalLength > 50) {
                    Serial.println("... (truncated for readability)");
                    break;
                }
            }
            
            // Method 2: Read full packet content as string
            Serial.println("\n--- Full packet content ---");
            String fullContent = "";
            for (size_t i = 0; i < totalLength; i++) {
                uint8_t byte = packetData[i];
                if (byte >= 32 && byte <= 126) {
                    fullContent += (char)byte;
                } else {
                    fullContent += ".";
                }
            }
            Serial.print("Content: \"");
            Serial.print(fullContent);
            Serial.println("\"");
            
            // Method 3: If packet contains JSON, try to identify it
            if (fullContent.indexOf("{") >= 0 && fullContent.indexOf("}") >= 0) {
                Serial.println(">>> JSON packet detected <<<");
                Serial.print("JSON: ");
                Serial.println(fullContent);
            }
            
            // Method 4: Show hex dump for binary data
            if (totalLength <= 100) { // Only for smaller packets
                Serial.println("\n--- Hex dump ---");
                for (size_t i = 0; i < totalLength; i += 16) {
                    Serial.print("0x");
                    if (i < 16) Serial.print("0");
                    Serial.print(i, HEX);
                    Serial.print(": ");
                    
                    // Print hex values
                    for (size_t j = 0; j < 16 && (i + j) < totalLength; j++) {
                        if (packetData[i + j] < 16) Serial.print("0");
                        Serial.print(packetData[i + j], HEX);
                        Serial.print(" ");
                    }
                    
                    // Print ASCII representation
                    Serial.print(" | ");
                    for (size_t j = 0; j < 16 && (i + j) < totalLength; j++) {
                        uint8_t byte = packetData[i + j];
                        if (byte >= 32 && byte <= 126) {
                            Serial.print((char)byte);
                        } else {
                            Serial.print(".");
                        }
                    }
                    Serial.println();
                }
            }
            
            Serial.println("================================");
        });
    } else {
        Serial.println("ERROR: Failed to start UDP server!");
        Serial.println("Check your WiFi connection and try again.");
    }
}

void loop() {
    // Main loop - UDP handling is done asynchronously
    // Show periodic status
    static unsigned long lastStatus = 0;
    if (millis() - lastStatus > 30000) { // Every 30 seconds
        Serial.print("Server running... Packets received: ");
        Serial.println(packetCount);
        lastStatus = millis();
    }
    
    delay(1000);
}

Example 2: UDP Client (Sender) – Testing Companion Code

This companion example demonstrates how to send UDP data to an ESP32 running the available() method example. It acts as a UDP client that sends various types of data packets to test the available() 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.2 (Fixed)
* License: MIT
* 
* Description: 
* This companion example demonstrates how to send UDP packets of various
* sizes to test the available() method functionality on the receiving ESP32.
* It acts as a UDP client that sends different packet sizes to help
* demonstrate the available() method capabilities. This is the CLIENT/SENDER code.
* FIXED VERSION - Corrected UDP sending issues and improved reliability.
*
* How to use this example (Client Setup):
* 1. First, upload and run the UDP Server code 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 packet transmission
* 6. Observe the server's Serial Monitor to see available() method 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 <WiFi.h>
#include <AsyncUDP.h>

// WiFi credentials - MUST BE THE SAME AS SERVER
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 = 8000;  // Send every 8 seconds (increased for better visibility)
int messageCounter = 0;

void setup() {
    Serial.begin(115200);
    delay(1000);
    
    Serial.println("=== UDP Client Sender Starting ===");
    
    // Convert server IP string to IPAddress object
    if (!serverIP.fromString(SERVER_IP)) {
        Serial.println("ERROR: Invalid server IP address format!");
        Serial.println("Please check the SERVER_IP constant.");
        while(1) delay(1000); // Stop execution
    }
    
    Serial.print("Target server IP: ");
    Serial.println(serverIP);
    Serial.print("Target server port: ");
    Serial.println(SERVER_PORT);
    
    // Connect to WiFi
    Serial.print("Connecting to WiFi");
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println();
    
    Serial.println("WiFi connected successfully!");
    Serial.print("Client IP address: ");
    Serial.println(WiFi.localIP());
    Serial.print("Client MAC address: ");
    Serial.println(WiFi.macAddress());
    
    // Test connectivity to server
    Serial.println("\nTesting connectivity to server...");
    Serial.println("Make sure the server is running and reachable!");
    Serial.println("================================");
    
    delay(2000); // Give time to read the setup info
}

void loop() {
    // Send different sized packets every 8 seconds
    if (millis() - lastSendTime >= sendInterval) {
        sendVariousSizedPackets();
        lastSendTime = millis();
        messageCounter++;
    }
    
    delay(100);
}

void sendVariousSizedPackets() {
    Serial.print("\n>>> SENDING TEST PACKETS (Round ");
    Serial.print(messageCounter + 1);
    Serial.println(") <<<");
    Serial.print("Timestamp: ");
    Serial.println(millis());
    
    // 1. Send minimal packet (1 byte) - more reliable than empty packet
    Serial.println("\n1. Sending minimal packet (1 byte)");
    uint8_t minimalData[] = {0xAA};  // Single byte marker
    size_t bytesSent = udp.writeTo(minimalData, sizeof(minimalData), serverIP, SERVER_PORT);
    Serial.print("   Bytes sent: ");
    Serial.print(bytesSent);
    Serial.println(bytesSent == sizeof(minimalData) ? "" : "");
    delay(1000);
    
    // 2. Send tiny packet (5 bytes) - binary data
    Serial.println("2. Sending tiny packet (5 bytes) - binary data");
    uint8_t tinyData[] = {0x01, 0x02, 0x03, 0x04, 0x05};
    bytesSent = udp.writeTo(tinyData, sizeof(tinyData), serverIP, SERVER_PORT);
    Serial.print("   Bytes sent: ");
    Serial.print(bytesSent);
    Serial.println(bytesSent == sizeof(tinyData) ? "" : "");
    delay(1000);
    
    // 3. Send small text packet (12 bytes)
    Serial.println("3. Sending small text packet (12 bytes)");
    String smallMessage = "Hello ESP32!";
    bytesSent = udp.writeTo((uint8_t*)smallMessage.c_str(), smallMessage.length(), serverIP, SERVER_PORT);
    Serial.print("   Message: \"");
    Serial.print(smallMessage);
    Serial.print("\" (");
    Serial.print(smallMessage.length());
    Serial.print(" bytes)");
    Serial.print(" - Bytes sent: ");
    Serial.print(bytesSent);
    Serial.println(bytesSent == smallMessage.length() ? "" : "");
    delay(1000);
    
    // 4. Send medium packet (50 bytes) - structured text
    Serial.println("4. Sending medium packet (50 bytes) - structured text");
    String mediumMessage = "This is a medium-sized UDP test packet from ESP32";
    bytesSent = udp.writeTo((uint8_t*)mediumMessage.c_str(), mediumMessage.length(), serverIP, SERVER_PORT);
    Serial.print("   Message length: ");
    Serial.print(mediumMessage.length());
    Serial.print(" bytes - Bytes sent: ");
    Serial.print(bytesSent);
    Serial.println(bytesSent == mediumMessage.length() ? "" : "");
    delay(1000);
    
    // 5. Send binary packet (64 bytes) - sequential pattern
    Serial.println("5. Sending binary packet (64 bytes) - sequential pattern");
    uint8_t binaryData[64];
    for (int i = 0; i < 64; i++) {
        binaryData[i] = (i % 256);  // Repeating pattern 0-255
    }
    bytesSent = udp.writeTo(binaryData, sizeof(binaryData), serverIP, SERVER_PORT);
    Serial.print("   Binary data size: ");
    Serial.print(sizeof(binaryData));
    Serial.print(" bytes - Bytes sent: ");
    Serial.print(bytesSent);
    Serial.println(bytesSent == sizeof(binaryData) ? "" : "");
    delay(1000);
    
    // 6. Send JSON packet (variable size)
    Serial.println("6. Sending JSON packet (structured data)");
    String jsonData = "{";
    jsonData += "\"round\":" + String(messageCounter + 1) + ",";
    jsonData += "\"sensor\":\"temperature\",";
    jsonData += "\"value\":25.4,";
    jsonData += "\"unit\":\"celsius\",";
    jsonData += "\"timestamp\":" + String(millis()) + ",";
    jsonData += "\"client_ip\":\"" + WiFi.localIP().toString() + "\",";
    jsonData += "\"rssi\":" + String(WiFi.RSSI());
    jsonData += "}";
    
    bytesSent = udp.writeTo((uint8_t*)jsonData.c_str(), jsonData.length(), serverIP, SERVER_PORT);
    Serial.print("   JSON size: ");
    Serial.print(jsonData.length());
    Serial.print(" bytes - Bytes sent: ");
    Serial.print(bytesSent);
    Serial.println(bytesSent == jsonData.length() ? "" : "");
    Serial.print("   JSON content: ");
    Serial.println(jsonData);
    delay(1000);
    
    // 7. Send large packet (200 bytes) - mixed content
    Serial.println("7. Sending large packet (200 bytes) - mixed content");
    String largeMessage = "LARGE_PACKET_START|";
    // Add padding to reach exactly 200 bytes
    for (int i = 0; i < 15; i++) {
        largeMessage += "0123456789";  // 10 chars each, 15 times = 150 chars
    }
    largeMessage += "|LARGE_PACKET_END";  // Add ending marker
    
    // Adjust to exactly 200 bytes
    while (largeMessage.length() < 200) {
        largeMessage += "X";
    }
    if (largeMessage.length() > 200) {
        largeMessage = largeMessage.substring(0, 200);
    }
    
    bytesSent = udp.writeTo((uint8_t*)largeMessage.c_str(), largeMessage.length(), serverIP, SERVER_PORT);
    Serial.print("   Large packet size: ");
    Serial.print(largeMessage.length());
    Serial.print(" bytes - Bytes sent: ");
    Serial.print(bytesSent);
    Serial.println(bytesSent == largeMessage.length() ? "" : "");
    
    Serial.println("\n>>> All test packets sent! <<<");
    Serial.println("Check the server's Serial Monitor for received data.");
    Serial.print("Next transmission in ");
    Serial.print(sendInterval / 1000);
    Serial.println(" seconds...");
    Serial.println("================================");
}

ESP32 Library Index

ESP32 Arduino Core Library


FAQ

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!

error: Content is protected !!