-->
Page 1 of 1

UDP packets do not send without calling delay

PostPosted: Thu Sep 24, 2015 4:50 am
by misterdanb
If I try to send UDP packets in my sketch, I have to put a delay(2); (below 2 does not work) into my loop function, otherwise the packet is never sent. If I put any delay directly after the endPacket(); call in the if condition (see below) it does not help at all, it has to be directly in loop.
As the code is somehow time critical, It would be awesome to omat those delay calls.
Any ideas?

Code: Select allvoid sendMessage(char message[])
{
#ifdef DEBUG
    Serial.print("Sending data: ");
    Serial.write(message, 5);
    Serial.println();
#endif

    udp.beginPacket(gameServer, gamePort);
    udp.write(message, 5);
    udp.endPacket();
}

void sendButtonsChanged(int newButtonStates)
{
    char message[] = {
        CMD_BUTTONS_CHANGED,
        char(newButtonStates & 0xFF),
        char((newButtonStates ^ buttonStates) & 0xFF),
        0x00,
        CMD_BUTTONS_CHANGED
    };

    sendMessage(message);
}

void sendKeepAlive()
{
    char message[] = {
        CMD_KEEP_ALIVE,
        char(buttonStates & 0xFF),
        0x00,
        0x00,
        CMD_KEEP_ALIVE
    };

    sendMessage(message);
}

void setup()
{
#ifdef DEBUG
    Serial.begin(115200);
#endif

    Cytrill.begin();
   
    setupWifi();
}

void loop()
{
    static int keepAliveCounter = 0;
   
    int newButtonStates = Cytrill.getButtons();

    if (newButtonStates != buttonStates)
    {
        sendButtonsChanged(newButtonStates);

        buttonStates = newButtonStates;
    }

    if (keepAliveCounter == 2000)
    {
        sendKeepAlive();
        keepAliveCounter = 0;
        //delay(20); // not helping at all
    }
    else
    {
        keepAliveCounter++;
    }

    delay(2); // helps

    Cytrill.loop();
}


Thanks in advance,

misterdanb

Re: UDP packets do not send without calling delay

PostPosted: Thu Sep 24, 2015 1:44 pm
by misterdanb
Duoble post, please delete one of them… My fault, sorry. :(

Re: UDP packets do not send without calling delay

PostPosted: Thu Oct 01, 2015 8:45 pm
by stang
I believe the issue is that you need to Yield the CPU - which is what the delay does from memory.

DOn't forget the ESP8266 has other stuff that runs in the background - including the physical layer handling.

Re: UDP packets do not send without calling delay

PostPosted: Sat Oct 03, 2015 9:58 pm
by mrburnette
A well-placed yield() will generally work. Here is my UDP sketch to broadcast GPS data:
https://www.hackster.io/rayburne/tardis-time-esp8266-ap-webserver-gps

Code: Select all  if (Serial.available() > 0) {
      char c = Serial.read();
      GPSstuff(c);
  }

  yield();

Ray