Need help getting two ESP32-C3 to communicate through WIFI

I kind of got side tracked on the LoRa stuff... so to conclude the post I am attaching my BASIC program that I used to test the ESP-NOW WIFI. this is a work in progress... I tried to stop the sent transmission if there is no response from the receiver and it does work sort of... the second unit that come "online" will have a different count for the packets because the first unit to go online sends the first set of packets before it looks for a callback response. My assumption at this point is the WIFI send buffer gets the first batch of packets and there is a WIFI buffer time out that sends the packet regardless if there is a response from the receiver. once the WIFI buffer empties my code to check for a response before it sends starts working and no other packet gets loaded into the WIFI buffer.... at least that is what I think happens... so basically the packet count NUMBER that is displayed on the serial monitor is off for the second ESP because the first ESP filled the send WIFI buffer with the first set of packets, sent out a packet, did NOT get a response, then waited X time, and sent the next packet anyway...
The code is the same for both units except changing the MAC Address where the packets will be sent to. Randomnerdstutoruals has a program to get the MAC address.
https://randomnerdtutorials.com/esp-now-esp32-arduino-ide/
I started working on connecting the serial of the ESP to the Teensy 4.1 and I commented this out...
Hope this helps someone...

Code:
//Most of the relevant code came from https://randomnerdtutorials.com/esp-now-esp32-arduino-ide/
//To get the MAC address of the ESP go to their site and they have a program that will display it on the serial monitor
// You need two ESP with WIFI and it will send packets from ESP1 to ESP2 and ESP2 to ESP1 the packet count is adjustable and the
// time between packet "SETS" is adjustable


#include <esp_now.h>
#include <WiFi.h>
//#include <HardwareSerial.h>  // To connect to the TEENSY 4.1
//HardwareSerial MySerial1(1);  // To connect to the TEENSY 4.1

// You need two ESP with WIFI
// REPLACE WITH YOUR RECEIVER MAC Address - Make sure it is the MAC address to the ESP you are Sending THE DATA TO...
uint8_t WIFI_broadcastAddress[] = {XXXX, XXXX, XXXX, XXXX, XXXX, XXXX};  //

// Structure example to send data
// Must match the receiver structure
typedef struct  WIFI_Incoming_Struct {
    char WIFI_Incoming_Packet[100];
} WIFI_Incoming_Struct;

// Create a struct_message called WIFI_Incoming_Packet_Struct_Variable
WIFI_Incoming_Struct WIFI_Incoming_Packet_Struct_Variable;

// Structure example to send data
// Must match the receiver structure
typedef struct  WIFI_Outgoing_Struct {
    char WIFI_Outgoing_Packet[100];
} WIFI_Outgoing_Struct;

// Create a struct_message called WIFI_Outgoint_Packet_Struct_Variable
WIFI_Outgoing_Struct WIFI_Outgoing_Packet_Struct_Variable;

esp_now_peer_info_t peerInfo;

/////////////////////////////////////////////////////////////////////////////////////
int WIFI_IncomingPacketCount = 0;
int WIFI_OutboundPacketCount = 0;
//int WIFI_Incoming_IntBufferArray[101] = {};
String WIFI_Incoming_StringBufferArray[101] = {};
int WIFI_Incoming_StringBufferArray_IndexSize = 100;
int WIFI_Incoming_StringBuffer_Write_Index = 0;
int WIFI_Incoming_StringBuffer_Last_Write_Index_SinceRead = 0;
int WIFI_Incoming_StringBuffer_Read_Index = 0;

int WIFI_SendPacket_SwitchCase = 0;

bool WIFI_OnDataSent_Fail_Flag = 0;  // 1 = Fail
uint64_t WIFITimerToResend = 0;
int WIFITimerToResend_TimeBetweenTries_Millis = 500;  // Adjusts the time between sets
int WIFITimerToResend_TryNumber = 1;
int WIFITimerToResend_MaxTries = 20;  // Adjust this to send more or less packets in a SET


int SwitchCase = 0;
uint32_t MillisTimer1 = 0;
uint32_t MillisTimer2 = 0;
uint32_t MillisTimerDifference = 0;

int PacketCounter = 1;
int PacketstoSendBeforeNextBreak = 0;
int PacketsBeforeBreak = 30;
int TimeBeforePacketSendResumes_Millis = 3000;
uint32_t PacketSendResumeTimer = 0;
int PacketNumber = 1;
String PacketString;
char PacketStringCharArray[100];



void setup() {
   // Init Serial Monitor
  Serial.begin(115200);

    // And configure MySerial1 on pins RX=D9, TX=D10  To connect to the TEENSY 4.1
   // MySerial1.begin(115200, SERIAL_8N1, 9, 10);
   // MySerial1.print("MySerial1");

  // Set device as a Wi-Fi Station
  WiFi.mode(WIFI_STA);

  // Init ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    return;
  }

  // Once ESPNow is successfully Init, we will register for Send CB to
  // get the status of Trasnmitted packet
  esp_now_register_send_cb(esp_now_send_cb_t(OnDataSent));

  // Once ESPNow is successfully Init, we will register for recv CB to
  // get recv packer info
  esp_now_register_recv_cb(esp_now_recv_cb_t(OnDataRecv));

  // Register peer
  memcpy(peerInfo.peer_addr, WIFI_broadcastAddress, 6);
  peerInfo.channel = 0;
  peerInfo.encrypt = false;

  // Add peer
  if (esp_now_add_peer(&peerInfo) != ESP_OK) {
    Serial.println("Failed to add peer");
    return;
  }
 delay(5000);  // to give me time to get the serial monitor up on my computer
}  // End Void Setup

//////////////////////////////////////////////////////////////////////////

void loop() {
//Print incoming data
  if (WIFI_Incoming_StringBuffer_Read_Index != WIFI_Incoming_StringBuffer_Write_Index) {
    Serial.print(WIFI_IncomingPacketCount);
    Serial.print(" ");
    Serial.println(WIFI_Incoming_StringBufferArray[WIFI_Incoming_StringBuffer_Read_Index]);
    if (WIFI_Incoming_StringBuffer_Read_Index >= WIFI_Incoming_StringBufferArray_IndexSize) {
      WIFI_Incoming_StringBuffer_Read_Index = 0;
    } else {
      WIFI_Incoming_StringBuffer_Read_Index++;
    }  // End Else
    WIFI_IncomingPacketCount++;
  }    // End if(WIFI_Incoming_StringBuffer_Last_Write_Index_SinceRead != WIFI_Incoming_StringBuffer_Write_Index)


// Send data
if(PacketSendResumeTimer <= millis()) {
if(PacketCounter > PacketstoSendBeforeNextBreak)  {
PacketstoSendBeforeNextBreak = PacketCounter + PacketsBeforeBreak;
PacketSendResumeTimer = millis() + TimeBeforePacketSendResumes_Millis;
} else {
PacketString = String(PacketNumber) + " " + "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
PacketString.toCharArray(PacketStringCharArray, PacketString.length() + 1);
 strcpy(WIFI_Outgoing_Packet_Struct_Variable.WIFI_Outgoing_Packet, PacketStringCharArray);
  WIFI_SendPacket();
  PacketCounter++;
 }// End else
  }  // End if(PacketSendResumeTimer <= millis())

  //delay(51);




}  // End Void Loop



void WIFI_SendPacket() {
  switch (WIFI_SendPacket_SwitchCase) {
    case 0:  {
      // Send message via ESP-NOW
      esp_err_t result = esp_now_send(WIFI_broadcastAddress, (uint8_t *)&WIFI_Outgoing_Packet_Struct_Variable, sizeof(WIFI_Outgoing_Packet_Struct_Variable));
      if (result == ESP_OK) {
        WIFI_SendPacket_SwitchCase = 1;
        // Serial.print("Out PC");
        //Serial.println(WIFI_OutboundPacketCount);
      } else {
        WIFI_SendPacket_SwitchCase = 2;
        Serial.println("Error sending the data OUT");
      }       // end else
      break;  // case 0
    } // End Case 0

    case 1:  {
      if (WIFI_OnDataSent_Fail_Flag == 0) {
        WIFI_SendPacket_SwitchCase = 0;
        PacketNumber++;
      } else {
        WIFI_SendPacket_SwitchCase = 2;
      }       // End else
      break;  // case 1
    }  // End case 1


    case 2:  {
      if (WIFITimerToResend < millis()) {
        esp_err_t result = esp_now_send(WIFI_broadcastAddress, (uint8_t *)&WIFI_Outgoing_Packet_Struct_Variable, sizeof(WIFI_Outgoing_Packet_Struct_Variable));
        if (result == ESP_OK) {
          WIFI_SendPacket_SwitchCase = 1;
        } else {
          Serial.println("Error Trying to resend the data");
        }  // end else

        WIFITimerToResend = (WIFITimerToResend_TimeBetweenTries_Millis * WIFITimerToResend_TryNumber) + millis();
        if (WIFITimerToResend_TryNumber > WIFITimerToResend_MaxTries) {
          WIFITimerToResend_TryNumber = WIFITimerToResend_MaxTries;
        } else {
          WIFITimerToResend_TryNumber++;
        }     // End else
      }       // End  if(WIFITimerToResend < millis())
      break;  // case 2
    }  // End case 2

  }  // End switch(WIFI_SendPacket_SwitchCase)

}  // End void WIFI_SendPacket()



// callback when data is sent
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  if (status == ESP_NOW_SEND_FAIL) {
    WIFI_OnDataSent_Fail_Flag = 1;
  } else {
    WIFI_OnDataSent_Fail_Flag = 0;
  }  //end else
}  // End void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status)


// callback function that will be executed when data is received
void OnDataRecv(const uint8_t *mac, const uint8_t *incomingData, int len) {
  memcpy(&WIFI_Incoming_Packet_Struct_Variable, incomingData, sizeof(WIFI_Incoming_Packet_Struct_Variable));
  if (WIFI_Incoming_StringBuffer_Write_Index >= WIFI_Incoming_StringBufferArray_IndexSize) {
    WIFI_Incoming_StringBuffer_Write_Index = 0;
  } else {
    WIFI_Incoming_StringBuffer_Write_Index++;
  }  // End else
  WIFI_Incoming_StringBufferArray[WIFI_Incoming_StringBuffer_Write_Index] = String(WIFI_Incoming_Packet_Struct_Variable.WIFI_Incoming_Packet);
}  //End void OnDataRecv(const uint8_t *mac, c.....
 
It's not real clear to me which devive initiates the coversation. In loop it "listens" but just once, then sends. I'm not sure there is ample listen time--at least that's what I see.

I have a similiar system in my house where a base communicates wirelessly with sensors around the house. The base is always in transmit mode and only listens after sending a request. Base sends a request to all sensors every 5 min. All sensors are alwasy in listen mode unless a valid request was received
Code:
// the base

loop()
    // if 5 min has passed
    // query each sensor (send a request the listen for a response)

    for i = 1 to 5 // cause I have 5 sensors
        // send
        send a struct (packet) to i // basically a struct with several data type and most importantly and ID field

        // listen and wait
        found data = false
        while elapsed time is less that 10 seconds // or some time
            if data was recieved
                if recieved ID = i
                    parse the data (get temperature, humidity, garage door status etc)
                    found data = true
                    break out of loop               
                endif
            endif
        end while
        if found data = true
            display sensor i results on a screen
        else
            display sensor i not found
        endif
    next
    

end loop


// the sensor

loop()

    // listen mode where we wait for a request
    if data received   
        if received ID = myID
            illuminate a LED // lets me know a request came in
            measure sensors
            build struct of sensor data
            // data broadcast and all sensor in listen mode but since ID's don't match, they ignore
            // base is temporarily in listen mode and know what id it sent and what Id came in
            send the struct
        else
            do nothing as request is not for me
        endif
        wait 2 seconds and turn LED off
    endif

end loop
, then the sensor sends data back and returns to listen mode. All sensors run the same code but each has a different ID. Here's some pseudo code for how my system works
 
Back
Top