Your new topic does not fit any of the above??? Check first. Then post here. Thanks.

Moderator: igrr

User avatar
By misterdanb
#29767 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
User avatar
By mrburnette
#30448 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