Communication with 2 ESP32

Hello,

i feel like an idiot using the World Wide Web. Either im to incompetet or im the first one trying to do this. I need a simple example to get two Integer from one ESP32 to another one. I realy hope you can help me with that, by sending a basic example.

Who knows, how much IoT stuff im going to program at home so i thought i will use one esp32 as an Access Point. It builds up the wifi and sends the integer. That ESP will also be the one to communicate with the Apple HomeKit, but thats a problem for future me. The secound ESP should connect to the first one and receive the two integer. For Basic example, it should just send it to serial monitor.

I've tried many examples from the www but nothing worked. I think mostly one esp just failed to connect to the other. Although he access Point seems to Work. At least it shows up at my wifi setting on phone. I Also connected my phone to it and it worked, but the code told me there is no client. Also tried chatGPT. But nothing worked, even after i got the solutions finally compiled.

I would really be happy, if someone just copies the most basic example here and i can build the rest of the code upon it. Tahnks to everyone! i apended my latest attempt. First one the AccessPoint, the other one the server.

Your topic has been moved to a different forum category as it does not relate to the Nano 33 IOT

I have no idea about your question or ESP32. I know that there is something called "ESP now". A search on the WWW should give you plenty to start with: esp now examples - Google Search

With ESP-Now, you either need to know the MAC address of the target peer, which you have to register, to send a direct unicast message; or use the address FF:FF:FF:FF:FF:FF (which you also have to register as a peer) to broadcast the message to anyone that might be in range listening. The receiver gets the MAC address of the sender. The number of peers is limited to around the mid-teens.

To avoid hard-coding those MAC addresses or making them part of a configuration, you can have one broadcast "I am here" and have the other receive that broadcast and unicast reply "Here are two integers".

BTW, there's a non-zero chance of other ESP32 things that aren't yours nearby. They will see your broadcasts, and you may get theirs.

In my limited testing, if the thing on either end has an active WiFi connection, that can degrade the sending and/or receiving of ESP-Now messages. The only combo that seemed reliable is that if you have a WiFi connection to an Access Point, you can send unicast messages. Sending broadcasts doesn't work, and receiving either kind is spotty.

I don't see it? If you're using ESP-Now, try disabling WiFi completely.

An alternative way is to use a button or any other external event to perform the pairing and then store the other ESP's mac address in the flash memory as is done for example to pair bluetooth devices.

Without WiFi and enabling long range mode, with ESPs equipped with an external antenna, I got to a significant distance (about 400m).
I've never done any tests with the WiFi connection active, but I'm curious about it and sooner or later I want to try.

Sorry i forgot about the Code. First One should be the accessPoint the secound the receiver. I think is should work, but i didnt.

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

const char *ssid = "ESP32_AccessPoint";
const char *password = "password";
const int udpPort = 12345;
WiFiUDP udp;

void setup() {
  
  Serial.begin(115200);
  WiFi.mode(WIFI_AP);
  WiFi.softAP(ssid, password);

}

void loop() {
  
  static int dataToSend = 10;
// Sending integer data over UDP to the MAC address of the second ESP32
  uint8_t mac[] = {0xB8, 0xF0, 0x09, 0xCC, 0x44, 0x50}; 
  udp.beginPacket(mac, udpPort);
  udp.write((uint8_t*)&dataToSend, sizeof(dataToSend));
  udp.endPacket();

  Serial.print("Sent: ");
  Serial.println(dataToSend);

  // Increment data for next transmission
  dataToSend++;
  delay(1000); // Adjust delay as needed
}
#include <WiFi.h>
#include <WiFiUdp.h>

const char *ssid = "ESP32_AccessPoint";
const char *password = "password";
const int udpPort = 12345;

WiFiUDP udp;

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
  }
}

void loop() {
  delay(1000);
  int receivedInt = receiveInteger();
  Serial.print("Received: ");
  Serial.println(receivedInt);
}

int receiveInteger() {
  int receivedInt = 0;
  
  int packetSize = udp.parsePacket();
  if (packetSize) {
    // Received packet available
    udp.read((uint8_t*)&receivedInt, sizeof(receivedInt));
  }
  
  return receivedInt;
}

You are working with a protocol of type IP, so mac should be a variable of type IPAddress.

Why do you use a MAC address?

This is a server-client arrangement. It's based on Rui Santos's examples in R.N.T. He used a temperature/humidity thingy, but I just wanted a number. There's a lot of stuff commented out.

Anyway, in the following the Client requests the Server's millis (its "time") 'once a second' and knocks that out on its LCD.

Some of the LCD stuff may appear strange (it's for a curious device, LCDBug, that I picked up several years ago), it boils down to -- Serial.print (string received);

Sorry, but the libraries used are ESP8266. I suspect there are ESP32 equivalents.

Server

// ESP8266_ServerClient_Server_03
//

// Import required libraries
#include <ESP8266WiFi.h>
#include "ESPAsyncWebServer.h"

// Set your access point network credentials
const char* ssid = "ESP8266-Access-Point";
const char* password = "123456789";

AsyncWebServer server(80);

float fTime;
char bufr [15];

void setup()
{
  // Serial port for debugging purposes
  Serial.begin(115200);
  Serial.println();
  
  // Setting the ESP as an access point
  Serial.print("Setting AP (Access Point) ");
  // Remove the password parameter, if you want the AP (Access Point) to be open
  WiFi.softAP(ssid, password);

  IPAddress IP = WiFi.softAPIP();
  Serial.print("AP IP addr: ");
  Serial.println(IP);

  server.on("/bigTime", HTTP_GET, [](AsyncWebServerRequest *request)
  {
    timeData();
    request->send_P(200, "text/plain", bufr);
  });

  bool status;
  
  // Start server
  server.begin();
}
 
void loop()
{
}

void timeData ()
{
  fTime = millis();
  fTime = fTime / 1000;
  dtostrf(fTime, 1, 1, bufr);  
}

Client

//  N.B. - If the Server biffs, the Client
//  cannot / does not recover on its own.
//  manual intervention (reset) is required

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>

#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti WiFiMulti;

const char* ssid = "ESP8266-Access-Point";
const char* password = "123456789";

//Your IP address or domain name with URL path
const char* serverNameTemp = "http://192.168.4.1/temperature"; // not used
const char* serverNameHumi = "http://192.168.4.1/humidity";    // not used
const char* serverNamePres = "http://192.168.4.1/pressure";    // not used
const char* serverNameMsecs = "http://192.168.4.1/bigTime";    // it gets used

const byte hsEnable = D6;  // highside switch (LCDBug)

//#include <Wire.h>

String temperature; // not used
String humidity;    // not used
String pressure;    // not used
String bigTime;

unsigned long previousMillis = 0;
const unsigned long interval = 1000; 

void setup() 
{
  LCDBugprep();   // Ready my LCDmodule

  Serial.begin(115200);
  Serial.println();
 
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("Conn'd to WiFi");

  Serial1.begin(9600);   // LCDBug
  delay(2000);
  eraseAll();  // →→ Serial1.write(0x0c); Clear Disp, Home  
}

void loop() 
{
  unsigned long currentMillis = millis();
  
  if(currentMillis - previousMillis >= interval) 
  {
    // Check WiFi connection status
    if ((WiFiMulti.run() == WL_CONNECTED)) 
    {
      //temperature = httpGETRequest(serverNameTemp);
      //humidity = httpGETRequest(serverNameHumi);
      //pressure = httpGETRequest(serverNamePres);
      bigTime = httpGETRequest(serverNameMsecs);
      //Serial.println("Temperature: " + temperature + " *C - Humidity: " + humidity + " % - Pressure: " + pressure + " hPa");
      
      // hereabouts, print info on LCD
      eraseAll();
      cursorPosition(0,1);
      Serial1.print(bigTime);   // in 02t this should be millis / 1000
      
      // save the last HTTP GET Request
      previousMillis = currentMillis;
    }
    else 
    {
      Serial.println("WiFi Disconnected");
    }
  }
}

String httpGETRequest(const char* serverName) 
{
  WiFiClient client;
  HTTPClient http;
    
  // Your IP address with path or Domain name with URL path 
  http.begin(client, serverName);
  
  // Send HTTP POST request
  int httpResponseCode = http.GET();
  
  String payload = "--"; 
  
  if (httpResponseCode>0) 
  {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    payload = http.getString();
  }
  else 
  {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }
  // Free resources
  http.end();

  return payload;
}

void cursorPosition (byte colPos, byte rowPos)
{
  //  -- LCDBug control --
  Serial1.write(0x18); // COL control
  Serial1.write(colPos); // COL position 
  Serial1.write(0x19); // ROW control
  Serial1.write(rowPos); // ROW position  
}

void eraseAll ()
{
  //  -- LCDBug control --  
  Serial1.write(0x0c); // Clear Disp, Home  
}

void LCDBugPrep ()
{
  //  -- LCDBug preliminaries --
  pinMode(hsEnable, OUTPUT);  
  digitalWrite(hsEnable, LOW);
  delay(2000);
  digitalWrite(hsEnable, HIGH);
  delay(1500);
  //  -- End LCDBug --  
}

Because i thought it would be easier. I dont need to set a static ip adress. MacAdress is already static.

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