Page 1 of 1

ESP-NOW: Concurrent Master and Slave

Posted: Thu Aug 01, 2019 10:43 pm
by RavenHawk
I am interested to use ESP-NOW as a means to transmit data between two ESP32's back and forth, - each ESP receives and sends data, taking turns. The example library provides an example sketch for Slave and one for Master, which allows for one-directional data flow. However, I would like to use ESP-NOW for two-way communication. Is it possible to combine both of these sketches to allow the data to flow in both directions at the same time?
Image
I'm assuming two ESP's won't be able to send data at the same exact time, so the best approach to start, I think, would be to wait until a packet has been received before sending one from the other end. Here's a snippet of code which I tried to use, but failed:

Code: Select all

void setup()
{
  Serial.begin(115200);
  WiFi.mode(WIFI_MODE_APSTA);
  // configure device AP mode
  configDeviceAP();
  // This is the mac address of the Slave in AP Mode
  Serial.print("AP MAC: ");
  Serial.println(WiFi.softAPmacAddress());
  Serial.print("STA MAC: ");
  Serial.println(WiFi.macAddress());
  // Init ESPNow with a fallback logic
  InitESPNow();
  // Once ESPNow is successfully Init, we will register for recv CB to
  // get recv packer info.
  esp_now_register_recv_cb(OnDataRecv);
  esp_now_register_send_cb(OnDataSent);
}

unsigned long nextManage;

void loop() 
{
  // In the loop we scan for slave
  ScanForSlave();
  // If Slave is found, it would be populate in `slave` variable
  // We will check if `slave` is defined and then we proceed further
  if (slave.channel == CHANNEL2)
  { // check if slave channel is defined
    // `slave` is defined
    // Add slave as peer if it has not been added already
    bool isPaired = manageSlave();
    nextManage = millis() + 10000;
    while (isPaired)
    {
      if (packetRecieved)
      {
        packetRecieved = false;
        // Send data to device
        sendData();
      }

      unsigned long t = millis();
      if (t > nextManage)
      {
        nextManage = t + 10000;
        // pair success or already paired
        isPaired = manageSlave();
      }
    }
    Serial.println("Slave pair failed!");
  }
}

Re: ESP-NOW: Concurrent Master and Slave

Posted: Sat Aug 03, 2019 2:09 am
by WiFive