Need help using ESP now and WIFI at the same time

Hey never made a project this big, so sorry for the messy code.
I want to send a combination of 5 characters to other esp32 (in the end I will have 3 esp's in total). Before I added Wifi ESP Now (just called it bluetooth in code) worked without problems, but after adding wifi only wifi works , esp now fails to send the packets.
How can I fix this? I know you probably won't use both at the same time, but this is just a project I want to play around with and I want it to work. Any ideas?

My code (sorry mixed german/english comments):

#include <U8g2lib.h>
#include <Wire.h>
#include <HardwareSerial.h>
#include <esp_now.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <WebServer.h>

#define MAX_TEXT_LENGTH 32
U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);
// Struktur für zu sendende Daten

const char* ssid = "SSID";
const char* password = "Pass";
const char* serverNameB = "IP"; // target ip
const char* serverNameA = "IP"; // own ip
WebServer server(80);  // Server auf Port 80



HardwareSerial SerialUART(1);
#define BTN_A 12
#define BTN_B 14
#define BTN_C 27
#define BTN_D 26
#define BTN_E 25
#define BTN_F 33
#define BTN_G 32
#define BTN_H 2
#define BTN_I 15
#define BTN_SEND 19
#define BTN_DELETE 18
#define BTN_MODE 5



String display_E = "...";
String display_Mode = "...";
String text = "";
String modes[] = {"Bluetooth", "Wlan", "Kabel", "RFID"};
bool textChanged = true;
bool modeChanged = true;
int currentMode = 0;
bool lastButtonStates[13] = {false}; // Array to store the last state of each button
typedef struct struct_message {
  char message[32];  // Platz für einen String von bis zu 31 Zeichen (+ 1 für Nullterminierung)
} struct_message;

struct_message myData;  // Datenstruktur für gesendete Daten
struct_message receivedData;  // Empfangene Datenstruktur

// MAC-Adressen der Peers
uint8_t peerAddress1[] = {0x08, 0xD1, 0xF9, 0xCE, 0x68, 0x78};  // Gerät 1
uint8_t peerAddress2[] = {0x24, 0x0A, 0xC4, 0xAB, 0x68, 0x78};  // Gerät 2

// Peer-Informationen
esp_now_peer_info_t peerInfo1;
esp_now_peer_info_t peerInfo2;

// Callback für gesendete Daten
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  Serial.print("Last Packet to: ");
  for (int i = 0; i < 6; i++) {
    Serial.print(mac_addr[i], HEX);
    if (i < 5) Serial.print(":");
  }
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? " Success" : " Fail");
}

// Callback für empfangene Daten
void OnDataRecv(const esp_now_recv_info_t *info, const uint8_t *incomingData, int len) {
  memcpy(&receivedData, incomingData, sizeof(receivedData));
  Serial.print("Received message: ");
  Serial.println(receivedData.message);
  display_E = receivedData.message;
  display_Mode = "Bluetooth";
}


void setup() {
  Serial.begin(115200);
  SerialUART.begin(115200, SERIAL_8N1, 16, 17);
  WiFi.mode(WIFI_AP_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
      delay(1000);
      Serial.println("Verbinde mit WLAN...");
    }

    Serial.println("Verbunden mit WLAN");
    Serial.print("IP Address: ");
    Serial.println(WiFi.localIP());
    Serial.print("MAC Address: ");
    Serial.println(WiFi.macAddress());
    // ESP32 A als HTTP-Server, um Daten zu empfangen
    server.on("/data", HTTP_POST, handlePostRequest);
    server.begin();


  // Initialize the display
  u8g2.begin();
  u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_ncenB08_tr);
  u8g2.drawStr(5, 10, "Mode:");
  u8g2.drawStr(5, 20, "Send:");
  u8g2.drawHLine(5, 30, 123);
  u8g2.drawStr(5, 40, "R:");
  u8g2.drawStr(5, 50, "V:");
  u8g2.sendBuffer();

  // Initialize buttons
  pinMode(BTN_A, INPUT_PULLUP);
  pinMode(BTN_B, INPUT_PULLUP);
  pinMode(BTN_C, INPUT_PULLUP);
  pinMode(BTN_D, INPUT_PULLUP);
  pinMode(BTN_E, INPUT_PULLUP);
  pinMode(BTN_F, INPUT_PULLUP);
  pinMode(BTN_G, INPUT_PULLUP);
  pinMode(BTN_H, INPUT_PULLUP);
  pinMode(BTN_I, INPUT_PULLUP);
  pinMode(BTN_SEND, INPUT_PULLUP);
  pinMode(BTN_DELETE, INPUT_PULLUP);
  pinMode(BTN_MODE, INPUT_PULLUP);


  // ESP-NOW starten
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    return;
  }
  
  esp_now_register_send_cb(OnDataSent);
  esp_now_register_recv_cb(OnDataRecv);
  
  // Peer 1 registrieren
  memcpy(peerInfo1.peer_addr, peerAddress1, 6);
  peerInfo1.channel = 0;
  peerInfo1.encrypt = false;
  if (esp_now_add_peer(&peerInfo1) != ESP_OK) {
    Serial.println("Failed to add Peer 1");
    return;
  }

  // Peer 2 registrieren
  memcpy(peerInfo2.peer_addr, peerAddress2, 6);
  peerInfo2.channel = 0;
  peerInfo2.encrypt = false;
  if (esp_now_add_peer(&peerInfo2) != ESP_OK) {
    Serial.println("Failed to add Peer 2");
    return;
  }
}

void loop() {
  server.handleClient();
  if (SerialUART.available()) {
    // Empfangene Nachricht lesen
    String receivedMessage = SerialUART.readStringUntil('\n');
    // Nachricht ausgeben
    Serial.println("Empfangen: " + receivedMessage);
    display_E = receivedMessage;
    display_Mode = "Kabel";
  }
  bool currentButtonStates[13] = {
    digitalRead(BTN_A) == LOW,
    digitalRead(BTN_B) == LOW,
    digitalRead(BTN_C) == LOW,
    digitalRead(BTN_D) == LOW,
    digitalRead(BTN_E) == LOW,
    digitalRead(BTN_F) == LOW,
    digitalRead(BTN_G) == LOW,
    digitalRead(BTN_H) == LOW,
    digitalRead(BTN_I) == LOW,
    digitalRead(BTN_SEND) == LOW,
    digitalRead(BTN_DELETE) == LOW,
    digitalRead(BTN_MODE) == LOW,
  };

  bool textChanged = false;
  bool modeChanged = false;

  for (int i = 0; i < 13; i++) {
      if (currentButtonStates[i] && !lastButtonStates[i]) {
        if (i < 9 && text.length() < 5) {
          char letter;
          switch (i) {
            case 0: letter = 'A'; break;
            case 1: letter = 'B'; break;
            case 2: letter = 'C'; break;
            case 3: letter = 'D'; break;
            case 4: letter = 'E'; break;
            case 5: letter = 'F'; break;
            case 6: letter = 'G'; break;
            case 7: letter = 'H'; break;
            case 8: letter = 'I'; break;
          }
          text += letter;
          textChanged = true;
        } else if (i == 9 && text.length() == 5) {
          
          if (currentMode == 0) {
            // Bluetooth senden

            text.toCharArray(myData.message, MAX_TEXT_LENGTH);

            // Nachricht an Peer 1 senden
            esp_err_t result1 = esp_now_send(peerAddress1, (uint8_t *)&myData, sizeof(myData));
            if (result1 == ESP_OK) {
              Serial.print("Sent to Peer 1: ");
              Serial.println(myData.message);
            } else {
              Serial.println("Error sending to Peer 1");
            }

            // Nachricht an Peer 2 senden
            esp_err_t result2 = esp_now_send(peerAddress2, (uint8_t *)&myData, sizeof(myData));
            if (result2 == ESP_OK) {
              Serial.print("Sent to Peer 2: ");
              Serial.println(myData.message);
            } else {
              Serial.println("Error sending to Peer 2");
            }
            text = ""; // Text zurücksetzen
            textChanged = true;
          }
          else if (currentMode == 1) {
            //Mode 2
            sendDataToESP32(text);
            text = ""; // Text zurücksetzen
            textChanged = true;
          }

          else if (currentMode == 2) {
            //Kabel
            Serial.println("Sending text: " + text);
            SerialUART.println(text);
            text = ""; // Text zurücksetzen
            textChanged = true;
          }    

          else if (currentMode == 3) {
            //Mode 4
            text = ""; // Text zurücksetzen
            textChanged = true;
          }


        } else if (i == 10 && text.length() > 0) {
          text.remove(text.length() - 1);
          textChanged = true;
        } else if (i == 11) {
          // Wechseln des Modus
          currentMode = (currentMode + 1) % 4;
          modeChanged = true;
        }
      }
      lastButtonStates[i] = currentButtonStates[i];
    }
    
  u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_ncenB08_tr);
  u8g2.drawStr(5, 10, "Mode:");
  u8g2.drawStr(45, 10, modes[currentMode].c_str());
  u8g2.drawStr(5, 20, "Send:");
  u8g2.drawStr(45, 20, text.c_str());
  u8g2.drawHLine(5, 30, 123);
  u8g2.drawStr(5, 40, "Empfangen:");
  u8g2.drawStr(75, 40, display_E.c_str());
  u8g2.drawStr(5, 50, "Mode:");
  u8g2.drawStr(45, 50, display_Mode.c_str());
  u8g2.sendBuffer();


  // Send the current text to the Serial Monitor if it has changed
  if (textChanged) {
    Serial.println("Current text: " + text);
  }

  // Send the current mode to the Serial Monitor if it has changed
  if (modeChanged) {
    Serial.println("Current mode: " + modes[currentMode]);
  }

  delay(50); // Debounce delay
}

void handlePostRequest() {
  String message = "Daten empfangen: " + server.arg("data");
  Serial.println(message);
  display_E = server.arg("data");
  display_Mode = "Wifi";
  // Bestätigung zurücksenden
  server.send(200, "text/plain", "Daten erfolgreich empfangen!");
}

// Funktion zum Senden von Daten an ESP32 B
void sendDataToESP32(String data) {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    http.begin(serverNameA);  // ESP32 B

    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    String httpRequestData = "data=" + data;
    int httpResponseCode = http.POST(httpRequestData);

    if (httpResponseCode > 0) {
      String response = http.getString();
      Serial.println("Antwort von ESP32: " + response);
    } else {
      Serial.println("Fehler beim Senden der Anfrage");
    }

    http.end();
  } else {
    Serial.println("WLAN-Verbindung verloren");
  }
}

Isn't esp-now built on top of WiFi? That would mean you can't use both at the same time.

Last time I tried mixing them: if the unit is connected to a WiFi access point

  • it cannot broadcast ESP-Now messages
  • it only receives ESP-Now messages intermittently

emphasis -- post No.16

ESP NOW and WIFI must work on the same channel. If for any reason your Wifi doesn't use Channel 1 you must bring the ESP NOW only node also to the other channel.

It will be far easier, when you can force your WIFI to channel 1.

Start with two simple sketches:

  • the ESP NOW only sketch at the correct WIFI Channel
  • a combined sketch with ESP NOW and Wifi

You don't need an OLED or lot of digital outputs to start with.

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