UDP.parsePacket() returns 0 when SYSTEM_MODE set to SEMI_AUTOMATIC/MANUAL [SOLVED]

When I set SYSTEM_MODE to SEMI_AUTOMATIC or MANUAL, the UDP.parsePacket() always returns 0. When I check WiFi.ready() it returns true, this means it is connected to WiFi and has an IP assigned. I am sending the UDP packet from the same network, so even if Spark Core is not connect to Cloud, the UDP should work, is it? But it is not when I set the SYSTEM_MODE other than AUTOMATIC. What I want is that my Spark Core does not want to connect to Cloud but it should receive UDP packets from local network.

My actual code is not this but, for debugging purpose I am using the following code from Spark Core documentation.

#include "application.h"

SYSTEM_MODE(SEMI_AUTOMATIC);

// UDP Port used for two way communication
unsigned int localPort = 8888;

// An UDP instance to let us send and receive packets over UDP
UDP Udp;

void setup() {
	// start the UDP
	Udp.begin(localPort);

	// Print your device IP Address via serial
	Serial.begin(9600);
}

void loop() {
	int packets = Udp.parsePacket();

	Serial.print("Parse Packet returned ");
	Serial.print(packets);
	Serial.print(", WiFi Status ");
	Serial.println(WiFi.ready());

	// Check if data has been received
	if (packets > 0) {

		// Read first char of data received
		char c = Udp.read();

		// Ignore other chars
		Udp.flush();

		// Store sender ip and port
		IPAddress ipAddress = Udp.remoteIP();
		int port = Udp.remotePort();

		// Echo back data to sender
		Udp.beginPacket(ipAddress, port);
		Udp.write(c);
		Udp.endPacket();
	}
}

I added Serial.print for debugging purpose, am I missing something here?

UPDATE #1: The code is working when you move UDP.begin() inside the loop() method. Following code works, I should have tried this before posting here :frowning:

if(WiFi.ready() && !isInitialized ){
	// start the UDP
	Udp.begin(localPort);

	isInitialized = true;
}

UPDATE #2: For MANUAL mode, you should call WiFi.connect()

2 Likes