Help with UDP send/receive

The following sketch is based on the JJRobots Brobot source for use with their Devia board that includes an ESP8266 chip. It is supposed to open a UPD port and allow for sending and receiving UDP data using ports 2223 and 2222. It was designed to work with TouchOSC on an iPhone or android.

What I provide here is pared down to just what is needed for the communications. So far, I haven’t been able to prove that it sends or receives.

It can be a standalone server or connected to an existing network. In standalone mode, you connect to the server and the connections are:

#define WIFI_IP "192.168.1.101”   // Force Server IP
#define TELEMETRY "192.168.1.38"  // Telemetry server port 2223

When connected to a network, the connections are:

#define TELEMETRY "192.168.4.2" // Default telemetry server (first client) port 2223

I am using “Packet Sender” to send "Hello" in a UDP packet.

In network connection mode, I sent a packet to 192.168.1.38 and 192.168.1.101 ports 2223 and 2222. Nothing showed up on the Serial Monitor

In standalone server mode, I sent packets to 192.168.4.2 and 192.168.1.101 ports 2223 and 2222. No luck.

Let me state that I know almost nothing about UDP communications. The Packet server is something I found when Googling “monitor UDP Packets”.

Not sure what is wrong. It may be as simple as the way I am trying to read/write in the loop().

Two questions:

  1. Why doesn’t the sketch display the packets that it is sent?
  2. Is Packet Sender a good tool to use for monitoring the UDP packets? It seems to send packets but it has never shown an incoming packet.

Added info on 11/15/2023
The Devia shield is on an Arduino Leonardo. The following is the Serial Monitor display when the sketch starts. The series of errors are NEW this morning.

I think the Devia board is just too much trouble. I am going to switch to the Arduino R4 Wifi.

UDP Server test
WIFI init

ERROR

ERROR
52

ERROR
4

ERROR
79

ERROR
79

ERROAT

OK

!Timeout!
AT+RST

OK

ets Jan 8 2013,rst cause:2, boot mode:(3,6)

load 0x401sl⸮⸮rl⸮⸮
Ai-Thinker Technology Co.,Ltd.

ready
!Timeout!
AT+CIPSTAMAC?

+CIPSTAMAC:"18:fe:34:df:00:64"

OK

AT+CWQAP

OK

AT+CWMODE=2

OK

AT+CWSAP="UDP_TEST_64","87654321",5,3

OK
Start UDP server

AT+CIPMUX=0

OK

AT+CIPMODE=1

OK

AT+CIPSTART="UDP","192.168.4.2",2223,2222,0

CONNECT

OK

Server Started


Here are the files:

UDPTest.ino

// BROBOT EVO 2 by JJROBOTS
// SELF BALANCE ARDUINO ROBOT WITH STEPPER MOTORS
// License: GPL v2
// OSC functions  (OSC = Open Sound Control protocol)
#include "secrets.h"
#include <Wire.h>
#define OSCDEBUG1
#define OSCDEBUG2
#define OSCDEBUG3

// Uncomment this lines to connect to an external Wifi router (join an existing Wifi network)
//#define EXTERNAL_WIFI
//#define WIFI_IP "192.168.1.101"  // Force ROBOT IP
//#define TELEMETRY "192.168.1.38" // Telemetry server port 2223

#define TELEMETRY "192.168.4.2" // Default telemetry server (first client) port 2223

String MAC;  // MAC address of Wifi module
bool newControlParameters = false;
bool modifing_control_parameters = false;

// OSC output variables
uint8_t OSCpage;
uint8_t OSCnewMessage;
float OSCfader[4];
float OSCxy1_x;
float OSCxy1_y;
float OSCxy2_x;
float OSCxy2_y;
uint8_t OSCpush[4];
uint8_t OSCtoggle[4];
uint8_t OSCmove_mode;
int16_t OSCmove_speed;
int16_t OSCmove_steps1;
int16_t OSCmove_steps2;

// INITIALIZATION
void setup()
{
  Serial.begin(115200); // Serial output to console
  delay(1000);
  Serial1.begin(115200);
  delay(1000);
  Serial.println("UDP Server test");

    // With the new ESP8266 WIFI MODULE WE NEED TO MAKE AN INITIALIZATION PROCESS
  Serial.println("WIFI init");
  Serial1.flush();
  Serial1.print("+++");  // To ensure we exit the transparent transmision mode
  delay(100);
  ESPsendCommand("AT", "OK", 1);
  ESPsendCommand("AT+RST", "OK", 2); // ESP Wifi module RESET
  ESPwait("ready", 6);
  ESPsendCommand("AT+GMR", "OK", 5);

#ifdef EXTERNAL_WIFI
  ESPsendCommand("AT+CWQAP", "OK", 3);
  ESPsendCommand("AT+CWMODE=1", "OK", 3);
  //String auxCommand = (String)"AT+CWJAP="+WIFI_SSID+","+WIFI_PASSWORD;
  char auxCommand[90] = "AT+CWJAP=\"";
  strcat(auxCommand, WIFI_SSID);
  strcat(auxCommand, "\",\"");
  strcat(auxCommand, WIFI_PASSWORD);
  strcat(auxCommand, "\"");
  ESPsendCommand(auxCommand, "OK", 14);
#ifdef WIFI_IP
  strcpy(auxCommand, "AT+CIPSTA=\"");
  strcat(auxCommand, WIFI_IP);
  strcat(auxCommand, "\"");
  ESPsendCommand(auxCommand, "OK", 4);
#endif
  ESPsendCommand("AT+CIPSTA?", "OK", 4);
#else  // Deafault : we generate a wifi network
  Serial1.println("AT+CIPSTAMAC?");
  ESPgetMac();
  //Serial.print("MAC:");
  //Serial.println(MAC);
  delay(200);
  ESPsendCommand("AT+CWQAP", "OK", 3);
  ESPsendCommand("AT+CWMODE=2", "OK", 3); // Soft AP mode
  // Generate Soft AP. SSID=UDP_TEST, PASS=87654321
  char *cmd =  "AT+CWSAP=\"UDP_TEST_XX\",\"87654321\",5,3";
  // Update XX characters with MAC address (last 2 characters)
  cmd[19] = MAC[10];
  cmd[20] = MAC[11];
  ESPsendCommand(cmd, "OK", 6);
#endif
  // Start UDP SERVER on port 2222, telemetry port 2223
  Serial.println("Start UDP server");
  ESPsendCommand("AT+CIPMUX=0", "OK", 3);  // Single connection mode
  ESPsendCommand("AT+CIPMODE=1", "OK", 3); // Transparent mode
  char Telemetry[80];
  strcpy(Telemetry,"AT+CIPSTART=\"UDP\",\"");
  strcat(Telemetry,TELEMETRY);
  strcat(Telemetry,"\",2223,2222,0");
  ESPsendCommand(Telemetry, "OK", 3); 
Serial.println("\nServer Started");
}

int incomingByte = 0;
void loop() {
  Serial1.print("Hello");
  delay(1000);
}

Network.ino

// BROBOT EVO 2 by JJROBOTS
// SELF BALANCE ARDUINO ROBOT WITH STEPPER MOTORS
// License: GPL v2
// OSC functions  (OSC = Open Sound Control protocol)

void readControlParameters()
{
  // Parameters Mode (page2 controls)
  // Parameter initialization (first time we enter page2)
  if (!modifing_control_parameters)
  {
    for (uint8_t i = 0; i < 4; i++)
      OSCfader[i] = 0.5;
    OSCtoggle[0] = 0;

    modifing_control_parameters = true;
    Serial1.println("$P2");
  }
}

int ESPwait(String stopstr, int timeout_secs)
{
  String response;
  bool found = false;
  char c;
  long timer_init;
  long timer;

  timer_init = millis();
  while (!found) {
    timer = millis();
    if (((timer - timer_init) / 1000) > timeout_secs) { // Timeout?
      Serial.println("!Timeout!");
      return 0;  // timeout
    }
    if (Serial1.available()) {
      c = Serial1.read();
      Serial.print(c);
      response += c;
      if (response.endsWith(stopstr)) {
        found = true;
        delay(10);
        Serial1.flush();
        Serial.println();
      }
    }
  }
  return 1;
}

// getMacAddress from ESP wifi module
int ESPgetMac()
{
  char c1, c2;
  bool timeout = false;
  long timer_init;
  long timer;
  uint8_t state = 0;
  uint8_t index = 0;

  MAC = "";
  timer_init = millis();
  while (!timeout) {
    timer = millis();
    if (((timer - timer_init) / 1000) > 5) // Timeout?
      timeout = true;
    if (Serial1.available()) {
      c2 = c1;
      c1 = Serial1.read();
      Serial.print(c1);
      switch (state) {
        case 0:
          if (c1 == ':')
            state = 1;
          break;
        case 1:
          if (c1 == '\r') {
            MAC.toUpperCase();
            state = 2;
          }
          else {
            if ((c1 != '"') && (c1 != ':'))
              MAC += c1;  // Uppercase
          }
          break;
        case 2:
          if ((c2 == 'O') && (c1 == 'K')) {
            Serial.println();
            Serial1.flush();
            return 1;  // Ok
          }
          break;
      }
    }
  }
  Serial.println("!Timeout!");
  Serial1.flush();
  return -1;  // timeout
}

int ESPsendCommand(char *command, String stopstr, int timeout_secs)
{
  Serial1.println(command);
  ESPwait(stopstr, timeout_secs);
  delay(250);
}

Secrets.h

#define WIFI_SSID "xxxx"
#define WIFI_PASSWORD "xxxx"

i'm not familiar with your use of "AT" commands. i have code (below) that send/receives broadcast UDP packets.

before any packets can be transmitted, the device much connect to the WiFi router using ssid/password. i only see the credentials used in one of you programs and am not sure if the are used properly.

this code has evolved over time, initially attempting to use TCP packet and have multiple sets of credentials that are matched against multiple routers (i.e. _wifiScan())

the following is state driven where wifiMonitor() is called within loop(). it checks for an ssid, then registers with the router, waits for it to connect and then monitors, listens for packets

#ifdef ESP32
# include <WiFi.h>
#elif defined(ESP8266)
# include <ESP8266WiFi.h>
#endif

#include "AsyncUDP.h"

#include "eeprom.h"
#include "node.h"
#include "signals.h"
#include "wifi.h"

int dbgWifi = 1;

static void _wifiScan (void);
static void _wifiMsg  (const char *msg);

// -----------------------------------------------------------------------------
// WiFiClient          wifi;
AsyncUDP udp;

char host [STR_SIZE] = "";
char ssid [STR_SIZE] = "";
char pass [STR_SIZE] = "";

static int  port  = 4445;

// ---------------------------------------------------------
enum { ST_NUL, ST_INIT, ST_CHK, ST_CFG_UDP, ST_UP, ST_ERROR };

const char *wifiStStr [] = {
    "ST_NUL",
    "ST_INIT",
    "ST_CHK",
    "ST_CFG_UDP",
    "ST_UP",
    "ST_ERROR"
};

int state    = ST_NUL;
int stateLst = ST_NUL;

// -------------------------------------
static bool
_wifiCheck (void)
{
    static int           fails = 0;
    static unsigned long msecLst = 0;

    if ( (msec - msecLst) < 1000)
        return false;
    msecLst = msec;

    printf (" %s:", __func__);

#if 0
    if (6 <= fails)  {
        _wifiScan ();
        return false;
    }
#endif

    if (WL_CONNECTED != WiFi.status ())  {
        printf (" not connected\n");
        fails++;
        return false;
   }

   IPAddress ip = WiFi.localIP ();

   printf (" connected %d:%d:%d:%d\n", ip [0], ip[1], ip [2], ip[3]);

   return true;
}

// -------------------------------------
// https://arduino.clanweb.eu/udp-control-esp32.php?lang=en

static void
_wifiCfgUdp (void)
{
    printf (" %s:\n", __func__);

    if (udp.listen (port)) {
        Serial.print ("  UDP Listening on IP: ");
        Serial.println (WiFi.localIP ());

        udp.onPacket ([] (AsyncUDPPacket packet) {
#if 0
            Serial.print   ("UDP Packet Type: ");
            Serial.println (packet.isBroadcast ()
                        ? "Broadcast"
                        : packet.isMulticast () ? "Multicast" : "Unicast" );
            Serial.print   (" From: ");
            Serial.print   (packet.remoteIP ());
            Serial.print   (":");
            Serial.println (packet.remotePort ());
            Serial.print   (" To: ");
            Serial.print   (packet.localIP ());
            Serial.print   (":");
            Serial.println (packet.localPort ());
            Serial.print   (" Length: ");
            Serial.println (packet.length ());
            Serial.print   (" Data: ");
            Serial.write   (packet.data (), packet.length ());
            Serial.println ();
#endif

            _wifiMsg ((const char *) packet.data ());
        });
  }
}

// -------------------------------------
// connect to wifi
void _wifiInit (void)
{
    printf (" %s:\n", __func__);

    _wifiScan ();
    WiFi.mode (WIFI_STA);

    WiFi.hostname (host);

    printf ("%s: ssid %s, pass %s\n", __func__, ssid, pass);
    WiFi.begin (ssid, pass);
}

// -------------------------------------
static void
_wifiMsg (
    const char *msg)
{
    printf (" %s:\n", __func__);

    sigMsg (msg);
}

// -------------------------------------
void
wifiReset (void)
{
    printf ("%s: ssid %s, pass %s, host %s\n", __func__, ssid, pass, host);
    state = ST_NUL;
}

// -------------------------------------
// https://openlabpro.com/guide/scanning-of-wifi-on-esp32-controller/
static void
_wifiScan (void)
{
    printf ("%s:\n", __func__);

    // WiFi.scanNetworks will return the number of networks found
    WiFi.mode (WIFI_OFF);
    int nNet = WiFi.scanNetworks ();
    if (nNet == 0) {
        printf ("  %s: no networks found\n", __func__);
    }
    else {
        printf ("  %s: %2d networks found\n", __func__, nNet);
        if (0 > nNet)
            nNet = -nNet;
        for (int i = 0; i < nNet; ++i) {
            printf (" %s: %2d - %s (%d) %s\n", __func__, i,
                WiFi.SSID (i).c_str (),
                WiFi.RSSI (i),
                WiFi.encryptionType (i) == WIFI_AUTH_OPEN ? "open" : "locked");
        }
    }
}

// ---------------------------------------------------------
// common routine for sending strings to wifi and flushing
void
wifiSend (
    const char*  msg )
{
    if (ST_UP != state)
        return;

    if (dbgWifi)  {
        printf ("wifiSend: %s\n", msg);
    }

    udp.broadcast (msg);
}

// -------------------------------------
void
wifiMonitor (void)
{
    if (stateLst != state)
        printf ("%s: %d %s\n", __func__, state, wifiStStr [state]);
    stateLst = state;

    switch (state)  {
    case ST_NUL:
        if (ssid [0])
            state = ST_INIT;
        else {
            printf ("%s: no SSID\n", __func__);
            state = ST_ERROR;
        }
        break;

    case ST_INIT:
        _wifiInit ();
        state = ST_CHK;
        break;

    case ST_CHK:
        if (_wifiCheck ())
            state = ST_CFG_UDP;
        break;

    case ST_CFG_UDP:
        _wifiCfgUdp ();
        state = ST_UP;
        break;

    case ST_UP:
        break;

    case ST_ERROR:
    default:
        break;
    }
}

Well, I just switched to the Arduino WIFI R4 and the UDP example for it works right out of the box.

No more messing with the Devia board.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.