UDP WiFi Sketch no longer working properly with ESP32-C3 Board

Last week the following sketch would print out the Humidity, Temperature in C and Temperature in F every 5 seconds in Terminal. :

// In Terminal use nc -ul 8080

#include <WiFi.h>
#include <WiFiUdp.h>
#include <DHT.h>

// -- DHT22 Setup --
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

const char* ssid = "888888888";
const char* password = "yyyyyyyyyyyyyyy";
const char* macIP = "192.168.1.223";
const uint16_t port = 8080;

WiFiUDP udp;

void setup() {
  dht.begin();
  WiFi.begin(ssid, password);
  WiFi.setTxPower(WIFI_POWER_8_5dBm); //to reduce power and enable quicker connection
  
  while (WiFi.status() != WL_CONNECTED) 
   delay(500);
}

void loop() {
  float h = dht.readHumidity();
  float tC = dht.readTemperature();
  float tF = dht.readTemperature(true);
  udp.beginPacket(macIP, port);
  udp.print("Humidity: ");
  udp.print(h);
  udp.println(" %RH");
  udp.print("Temp C: ");
  udp.print(tC);
  udp.println(" °C");
  udp.print("Temp F: ");
  udp.print(tF);
  udp.println(" °F");
  udp.println();
  udp.endPacket();
  delay(5000);
}

Today in prints the data out once only! The sketch hasn't changed the board hasn't changed but I know there has been an update to the ESP32 boards by Espressif. I got two new ESP32 boards and have been playing about with them and ESPNOW. Could I have done anything to corrupt the IDE, it has crashed a couple of times when working with the new boards? I have been tearing my hair out for the last 2 days but just cannot get the sketch to work as it should. Can anyone offer any works of wisdom please? I am on an iMAC, Arduino IDE 2.3.6 and ESP32 boards version 3.3.10 by Espressif.

I rolled back ESP32 to 3.3.8, no joy, I updated to IDE 2.3.10, no joy any help would be very much appreciated.

You already have another topic on the same subject

See it for answers

WiFiUDP is actually NetworkUDP, which uses log_e in several places when things go wrong. To see these messages, add the usual Serial.begin(115200) in setup. Then before uploading, in the middle of the Tools menu, set Core Debug Level: change from None to Error.

You might change the title of this topic to indicate UDP, to differentiate from your original ESP-NOW and more recent IDE crashing issues.

I should have made it a separate topic from the start as it is different from the original.

if i run this UDP chat program

// ESP32 UDP chat program

#include <WiFi.h>
#include <WiFiUdp.h>

// network SSID (network name). and network password.
char ssid[] = "xxxxx";
char pass[] = "yyyyyyyyyyyyyyyyyy";

// UDP information
unsigned int localPort = 10000;   // local port to listen on
unsigned int remotePort = 10000;  // remote port to transmiit too
WiFiUDP udp;

IPAddress remoteIP(192, 168, 1, 65);
;  // IP will be entered as text

void setup() {
  Serial.begin(115200);
  while (!Serial) delay(1);
  delay(1000);
  Serial.setTimeout(60000l);
  Serial.println();
  Serial.println("\n\nESP32 WiFi UDP chat - send/receive UDP datagrams ");
  WiFi.mode(WIFI_STA);  // Connect to Wifi network.
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {  // Wait for connection
    delay(500);
    Serial.print(".");
  }
  Serial.print("\nGateway IP address: ");
  Serial.println(WiFi.gatewayIP());
  Serial.print("UDP started ");
  displayIPaddress(WiFi.localIP(), localPort);
  // Begin udp port
  udp.begin(localPort);
  Serial.print("Opening udp port ");
  Serial.println(localPort);
  // get remote IP address
  remoteIP = getIPaddress("\nenter remote IP address (e.g. 192.168.1.176)? ");
  Serial.print("\nRemote ");
  displayIPaddress(remoteIP, remotePort);
}

void loop() {
  if (Serial.available()) {  // if Serial text available send as a datagram
    udp.begin(localPort);
    char text[100] = { 0 };
    Serial.readBytesUntil('\n', text, 100);
    Serial.print("Transmitting to ");
    displayIPaddress(remoteIP, remotePort);
    Serial.println(text);
    udp.beginPacket(remoteIP, remotePort);  // transmit datagram
    udp.print(text);
    udp.endPacket();
  }
  int packetSize = udp.parsePacket();  // check if datagram received
  if (packetSize) {
    Serial.print("Received packet of size ");
    Serial.println(packetSize);
    Serial.print("From ");
    displayIPaddress(udp.remoteIP(), udp.remotePort());
    // read the packet into packetBuffer
    char packetBuffer[100] = { 0 };      // buffer to hold incoming packet,
    udp.read(packetBuffer, packetSize);  //UDP_TX_PACKET_MAX_SIZE);     // receive datagram
    Serial.print("Contents: ");
    Serial.println(packetBuffer);
  }
}

// read IP address from keyboard and check it
IPAddress getIPaddress(const char* prompt) {
  IPAddress ip;
  while (1) {  // read  IP (end with new line)
    Serial.print(prompt);
    while (Serial.available() == 0) delay(10);
    char text[40] = { 0 };
    Serial.readBytesUntil('\n', (char*)text, 40);
    for (int i = 0; i < 40; i++)
      if (text[i] < ' ') text[i] = 0;  // remove CR or LF
    Serial.print(text);
    if (ip.fromString(text)) break;  // if IP OK break while
    Serial.println(" invalid IP try again");
  }
  return ip;
}

// print IPAdress and port
void displayIPaddress(const IPAddress address, unsigned int port) {
  Serial.print(" IP ");
  for (int i = 0; i < 4; i++) {
    Serial.print(address[i], DEC);
    if (i < 3) Serial.print(".");
  }
  Serial.print(" port ");
  Serial.println(port);
}

and this version of your program from post 1 (DHT code commented out and network values updated)

// In Terminal use nc -ul 8080

#include <WiFi.h>
#include <WiFiUdp.h>
//#include <DHT.h>

// -- DHT22 Setup --
#define DHTPIN 2
#define DHTTYPE DHT22
//DHT dht(DHTPIN, DHTTYPE);

const char* ssid = "xxxxxxxxxx";
const char* password = "yyyyyyyyyyyyyy";
const char* macIP = "192.168.1.182";
const uint16_t port = 10000;//8080;

WiFiUDP udp;

void setup() {
  Serial.begin(115200);
  //dht.begin();
  WiFi.begin(ssid, password);
  WiFi.setTxPower(WIFI_POWER_8_5dBm); //to reduce power and enable quicker connection
  
  while (WiFi.status() != WL_CONNECTED) 
   delay(500);
}

void loop() {
  static int loop=0;
  Serial.printf("loop %d\n", loop);
  float h = 22.5+loop;//dht.readHumidity();
  float tC = 97.6+loop;//dht.readTemperature();
  float tF = 54.3+loop;//dht.readTemperature(true);
  loop++;
  udp.beginPacket(macIP, port);
  udp.print("Humidity: ");
  udp.print(h);
  udp.println(" %RH");
  udp.print("Temp C: ");
  udp.print(tC);
  udp.println(" °C");
  udp.print("Temp F: ");
  udp.print(tF);
  udp.println(" °F");
  udp.println();
  udp.endPacket();
  delay(5000);
}

the UDP chat program prints

ESP32 WiFi UDP chat - send/receive UDP datagrams 
...
Gateway IP address: 192.168.1.254
UDP started  IP 192.168.1.182 port 10000
Opening udp port 10000

enter remote IP address (e.g. 192.168.1.176)? 192.168.1.156
Remote  IP 192.168.1.156 port 10000
Received packet of size 61
From  IP 192.168.1.199 port 51519
Contents: Humidity: 22.50 %RH
Temp C: 97.60 °C
Temp F: 54.30 °F


Received packet of size 61
From  IP 192.168.1.199 port 51519
Contents: Humidity: 23.50 %RH
Temp C: 98.60 °C
Temp F: 55.30 °F

Received packet of size 61
From  IP 192.168.1.199 port 51519
Contents: Humidity: 24.50 %RH
Temp C: 99.60 °C
Temp F: 56.30 °F


Received packet of size 62
From  IP 192.168.1.199 port 51519
Contents: Humidity: 25.50 %RH
Temp C: 100.60 °C
Temp F: 57.30 °F


Received packet of size 62
From  IP 192.168.1.199 port 51519
Contents: Humidity: 26.50 %RH
Temp C: 101.60 °C
Temp F: 58.30 °F

prints the received packet every 5 seconds

try printing something in your transmitter loop() to check it is looping? e.g.

loop 0
loop 1
loop 2
loop 3
loop 4
loop 5
loop 6
loop 7

both devices are ESP32-C3

@horace

What IP addresses do I need for this program?

What I originally wanted (and had working) was for a single ESP32-C3 to print out the data from the temperature sensor every 5 seconds to the Terminal

but all I am getting is a single temperature from one loop. In using your corresponding sketch, I can see the loops counting in the serial monitor. If I could get your UDP chat sketch working with my sketch, that would be a start, but I am unsure what I need to add and where to get the info from. BTW it is port 10000 I used, I just didn't alter the script!

in your application the chat program is the receiver and displays its IPaddress and listen port

UDP started  IP 192.168.1.182 port 10000

your program should transmit to this address - edit the port if required

it does ask for the IPaddress to transmit too but as your program does not receive enter any IPaddress

enter remote IP address (e.g. 192.168.1.176)? 192.168.1.156

@horace

Apologies Horace, but I don't understand what exactly I need to do here! I take it I am loading the UDP Chat program onto one ESP32-C3 and the amended code of my sketch onto another. Not sure what you're getting at with the IP addresses other than I will be prompted to enter an IP address which can be anything! In the UDP chat program is the IPAddress remoteIP(192.168.1.65) the IP address of the second ESP32-C3? Of so is that all I need to do to get it running? Apologies if I seem a bit thick but I am new to ESP32 projects

I looked at a different way of transferring the temperature data to Terminal using wifi.server instead of UDP WiFi, as it appeared there was no solution. The wifi.sever method is working perfectly so I will regard this as a solution.

@horace I would be interested in getting the UDP Chat sketch working though for possible future projects

A massive thank you to all who contributed to this topic, it is very much appreciated.

UDP is connectionless so any node on the network, given suitable software, can chat to any other
the critical thing is they have to know each other's IPaddress and the ports to use

compile link and upload the UDPchat program to two ESP32 micros

they both connect to the WIfI network and print their IPaddresses e.g. fitst ESP32 prints

UDP started  IP 192.168.1.182 port 10000

on the second ESP32 when it askes for the remote IP you enter the IPaddress of the first, e.g.

enter remote IP address (e.g. 192.168.1.176)? 192.168.1.182

simillarly on the first ESP32 enter the IPaddress of the second ESP32
they can then chat to each other

the UDP chat program need not be an ESP32 so long as it can connect the the network, e.g. a Java program running on a PC (Windows, Linux, etc)

// UDPchat.java - simple peer-to-peer chat program using UDP
//           - given remote IP address can send strings using UDP datagrams 
//           - will also wait for datagrams and display contents
// remote IP and port are specified via command line - default IP is 127.0.0.1 (i.e. localhost) and port is 1000  
//
// e.g. to send datagrams to IP 146.227.59.130 port 1006
// java chat 146.227.59.130 1006

import java.io.*;
import java.util.*;
import java.net.*;

public class UDPchat extends Thread
{
   private final static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
   int port=10000;//999;//10001;// 100006                             // port to send/receive datagrams on
   String remoteIPaddress= "192.168.1.176";//"169.254.144.20";//("192.168.1.8");//127.0.0.1");      // IP to send datagrams

   // constructor, parameter is command line parameters
   public UDPchat(String args[]) throws Exception
    {
    // get remote IP address and port from command line parameters
    if (args.length > 0)    remoteIPaddress =  (args[0]);           // get IPaddress
    if (args.length > 1)    port = Integer.parseInt(args[1]);        // get port number
    System.out.println("chat program: IP address " + InetAddress.getLocalHost().toString() + " port " + port );
    
    start();        // start thread to receive and display datagrams

    // loop waiting for keyboard input, send datagram to remote IP                
    while(true)
      try
        {
        String s = in.readLine();                       // read a String
        System.out.println("Sending to " + remoteIPaddress + " socket " + port + " data: " + s);
        byte[] data = s.getBytes();                                     // convert to byte array
        DatagramSocket theSocket = new DatagramSocket();                // create datagram socket and the datagram
        DatagramPacket   theOutput = new DatagramPacket(data, data.length, InetAddress.getByName(remoteIPaddress), port);
        theSocket.send(theOutput);                                      // and send the datagram
       }
      catch (Exception e) {System.out.println("Eroor sending datagram " + e);}
    }

   // thread run method, receives datagram and display contents as a string
   public void run()                
        {
          try
              {
              // open DatagramSocket to receive 
              DatagramSocket ds = new DatagramSocket(port);
              // loop forever reading datagrams from the DatagramSocket
              while (true)
                 {
                 byte[] buffer = new byte[65507];                       // array to put datagrams in
                 DatagramPacket dp = new DatagramPacket(buffer, buffer.length); // DatagramPacket to hold the datagram
                 ds.receive(dp);                                     // wait for next datagram
                 String s = new String(dp.getData(),0,dp.getLength());        // get contenets as a String
                 System.out.println("UDP datagram length " + s.length()+ "  from IP " + dp.getAddress() + " received: " + s );
                 }
              }
          catch (SocketException se) {System.err.println("chat error " + se); }
          catch (IOException se) {System.err.println("chat error " + se);}
          System.exit(1);                                                       // exit on error
        }


public static void main(String args[]) throws Exception
{
   UDPchat c=new UDPchat(args);
}

}

@horace

Is this without amending anything beforehand? This is all I get:

I thought I would need to put the IP address of the ESP32 in first?

the ........... indicate it is not connecting to your WiFi
it should connect, displays its IP address then ask for the remote IP, e.g.

ESP32 WiFi UDP chat - send/receive UDP datagrams 
...
Gateway IP address: 192.168.1.254
UDP started  IP 192.168.1.182 port 10000
Opening udp port 10000

enter remote IP address (e.g. 192.168.1.176)? 

check you WiFi SSID and password?

@horace

It doesn't like my ESP32-C3 boards but fine with my ESP32 boards!

So let me get this right:

  1. I load the UDP Chat program to both ESP32 boards
  2. I type in the reciprocal IP addresses
  3. Load my program into one of the boards.

Is the output on Terminal or the serial monitor?

yes - to test load UDPchat program onto both modules

I ran the program of post 5 on a pair of ESP32-C3 modules - a ESP32-C3 supermini and a ESP32-C3-MINI-1
the output is to the Serial monitor - some ESP32-3 modules (e.g. ESP32-C3 supermini) require Tools>Board “USB CDC on boot” enabled

@

When both ESP32s are running the UDP Chat sketch, after typing them in, each one confirms the remote IP Address, is that correct?

I then loaded the other sketch onto one of the boards, it printed out the loop number in the serial monitor, nothing else appeared and nothing appeared on the other serial monitor.

I think I must be missing something!

yes - and you should be able to send text between the two modules

@horace

Yes, I have got the chat function working fine. In trying to get the other sketch loaded up and running, the IDE has crashed 4 times!

the IDE crashing is not good
what is the host operating system and the IDE version?

@horace

I am on OS Tahoe 26.5.1 and IDE 2.3.10

I restarted my Mac and got this message when I opened the IDE

I closed it down but it didn't come up when I opened it again!

Loaded the other sketch, typed in the IP address. The UDP chat sketch acknowledged it but nothing! The other Serial Monitor just gave the loop numbers.

@horace @kenb4 @anon95813201

I am getting these error messages since the IDE crashed and I got the message shown in post #19 above:

Can anyone tell me what I need to do to correct them please