UDP
begin()
Initializes the UDP library and network settings.
// SYNTAX
Udp.begin(port);
// PROTOTYPE
uint8_t begin(uint16_t port, network_interface_t nif=0);
If using SYSTEM_THREAD(ENABLED)
, you'll need
to wait until the network is connected before calling Udp.begin()
. With Device OS 6.2.0 and later, system thread is always enabled.
If you are listening on a specific port, you need to call begin(port) again every time the network is disconnected and reconnects, as well.
const int LISTENING_PORT = 8080;
SYSTEM_THREAD(ENABLED);
UDP udp;
bool wasConnected = false;
void setup() {
}
void loop() {
// For Wi-Fi, use WiFi.ready()
if (Cellular.ready()) {
if (!wasConnected) {
udp.begin(LISTENING_PORT);
wasConnected = true;
}
}
else {
wasConnected = false;
}
}
nif
is the network interface to bind to. This is typically omitted, in which case the primary network
inteface is used (cellular or Wi-Fi). You can, however pass Ethernet
, WiFi
, or Cellular
as this
parameter, which will bind to that specific interface. This is most commonly used when you use cellular
as your cloud connection, but listen for UDP packets on Ethernet from an isolated Ethernet LAN.
In Device OS 6.2.0 and later, nif
can be Tether
to allow UDP to and from another device
such as a Raspberry Pi connected by UART serial.