MKR WiFi 1010 UDP broadcasts stop after a few packets

I’m using a MKR WiFi 1010 and my program sends a UDP broadcast every 10 seconds. The broadcast contains a small JSON document.

This all goes well for about 5 to 10 packets, and then the broadcasts just stop. I’ve observed that:

  • WiFiUdp::endPacket() begins returning 0/false, which I presume means “not sent”, by why?
  • WiFiUdp::getWriteError() always returns 0
  • WiFi::getStatus() always returns 3 (WL_CONNECTED)

SO from that I can’t really work out what’s going wrong. I know the sketch is still sending the broadcasts (I’ve debugged it in VisualMicro) but they are no longer coming out of the WiFi chip.

Can anyone suggest what might be going on? Or failing that ideas for further analysis?

One thing I’ve noticed is that to get any broadcasts to happen at all, it is necessary to issue Udp.begin(port) which starts a listener on the given port. Well I didn’t really want to listen, but hey, it looks like I have to. However, that makes me thing that actually there’s something wrong with the way I’m initializing the stack. So here’s my init code…

void NetStateInitialize::onEnter()
{
statusIndicator = Cadence::Pulse1;
if (WiFi.status() == WL_NO_MODULE)
{
std::cout << “No WiFi module” << std::endl;
machine.changeState(new NetStateDisabled(machine));
return;
}

const std::string firmwareVersion = WiFiClass::firmwareVersion();
if (firmwareVersion < “1.2.1”)
{
std::cout << “WiFi firmware too old” << std::endl;
machine.changeState(new NetStateDisabled(machine));
return;
}

// attempt to configure to the Wifi network
WiFi.end(); // terminate any previous connection
WiFi.setHostname(“skynet”);
WiFi.noLowPowerMode();
WiFi.setTimeout(Timer::Seconds(5)); // AP Association timeout for WiFi.begin()
switch (WiFi.status())
{
case WL_FAILURE:
case WL_AP_FAILED:
case WL_CONNECT_FAILED:
case WL_NO_MODULE:
machine.changeState(new NetStateDisabled(machine));
break;
default:
machine.changeState(new NetStateAssociate(machine));
}
}

…and then later…

void NetStateAssociate::StartAccessPointAssociation()
{
stateTimer.SetDuration(AssociateRetryInterval);
++retryCount;
WiFi.begin(Secret::ssid, Secret::encryptionKey);
}

…and (about every 10 seconds)…

// WiFiUdp sender;

void NetStateOnline::sendJson(const JsonDocument& json)
{
//auto broadcastAddress = IPAddress(255, 255, 255, 255);
sender.begin(65000);
sender.beginPacket(machine.broadcastAddress, Configuration::BroadcastPort);
serializeJson(json, sender);
sender.println();
sender.endPacket();
}

First: Use code tags to post code! (That’s the </> button in the editor)

Second: Post complete code! Usually the error is in the part that isn’t posted.