UDP output locking out

I have produced a simple project that has buttons on all the digital inputs and output a UDP command depending on which button was pressed. I have this working but the command Stop coming out after I have sent 8 command until I either reconnect to the cloud or leave it for about 5 mins and it does an auto sync with the cloud.
I have tried it not connected to the cloud and i can only get it to send out once. I would like it not to be connected to the cloud as some of the projects i am going to use this on do not have internet access.

Code i am using

    //UDP Setup
byte ipAddress[] = { 192, 168, 0, 61};
UDP Udp;

    // Button setup
int W1A = 0;  //white 1
int W1B = 0;  //white 1 CONTROL

void setup() {
   
 //Pin Setup.
pinMode(D0, INPUT_PULLUP);
pinMode(D1, INPUT_PULLUP);

    //UDP Setup
Udp.begin(1024);
Udp.beginPacket(ipAddress, 1024);
Udp.write("Connected\r\n");
Udp.endPacket();

Spark.disconnect();    
}
void loop() {
    
// Button setup
W1A = digitalRead(D0);  //white 1
if (W1A == LOW){
    if (W1B == 0){
        W1B = 1;
        Udp.begin(1024);
        Udp.beginPacket(ipAddress, 1024);
        Udp.write("WHITE1\r\n");
        Udp.endPacket();
    }
}
else if (SLO == LOW){
    if (Spark.connected() == false){
        Spark.connect();
    }
    else {Spark.disconnect();
    }
}

else {
    W1B = 0;}
}

Hope someone can help me solve this problem.

Hi @leeeng

You are calling Udp.begin() twice without ever calling stop, so that will open a new socket every time you call it. There are only seven total sockets available.

Maybe you could try it without the Udp.begin() call in loop.

Also, how are you de-bouncing your switch input? You might get multiple packets from that too.

Thanks @bko

I am using the W1B as my de-bouncing on my switch
after it checks W1B to be 0 my script sets it to 1 and my last line if all is false then its change back to 0
i will try it with out the Udp.begin()

NOTE - Just tried this and it has worked Thanks. Do you know how long it will hold the socket open for?
or would it be cleaner to close the socket each time?

The socket will be open until you close it! Eventually when you run out of sockets, the TI part will generate an error and there is a (something like) 7 second timeout before it closes sockets and recovers.

It looks like you only need one socket, so I would open just the one. If you want to do error recovery, you might want to conditionally do Udp.begin() inside an if statement in loop() rather than just in setup(). So you have a flag you set to force Udp.stop() and then Udp.begin(port) again, if you detect a problem.