UDP Communication

Overview

This chapter introduces how to use UDP (User Datagram Protocol) for network communication in MicroPython. UDP is a connectionless, datagram-oriented protocol suitable for scenarios requiring high real-time performance but not data reliability.

MicroPython provides a lightweight usocket module that allows UDP communication on resource-constrained devices.

Prerequisites

  • Successfully connected to Wi-Fi or Ethernet network (depending on device)

  • Device supports the usocket module

UDP Client Example

The following example shows how to create a UDP client that sends data to a specified address and port:

import usocket

udp = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM)

server_ip = "192.168.1.100"
server_port = 5005
message = b"Hello, UDP Server"

udp.sendto(message, (server_ip, server_port))
udp.close()

UDP Server Example

The following example shows how to create a UDP server that listens on a specified port and receives data:

import usocket

udp = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM)
udp.bind(("0.0.0.0", 5005))

print("Listening on UDP port 5005...")

while True:
    data, addr = udp.recvfrom(1024)
    print("Received from {}: {}".format(addr, data))

Notes

  • UDP is a connectionless protocol and does not guarantee packet delivery or ordering.

  • Data size is limited by MTU; it is generally recommended to send less than 1472 bytes each time.

  • Call close() before closing the socket to avoid resource leaks.

Application Scenarios

  • LAN broadcast or multicast communication

  • Low-latency IoT data upload

  • Real-time sensor data transmission