0

I'm a total noob and just starting out with PlatformIO and Arduino/ESP32. I also want to say thanks in advance to any help I can get.

Plan:

I have 2 ESP32's talking over ESP_NOW, I just can't verify the data being sent in order to progress with my project. Basically, I have a Nextion display that sends specific info to an ESP32 (tested and working) and that ESP32 is then to send that information via ESP_NOW to the other ESP32 which will translate it into serial data to send to an Arduino Due and perform some tasks.

Problem:

The issue I have is that when I test, I see the data I think I am transmitting, but when I try to Serial.print said info, I get "0 0 0 0". I'm not sure that I am sending OR receiving the data properly. All I know is that when I press the button on the Nextion, I get a response on the ESP32 that is not connected.

Code:

#include <Arduino.h>
#include <esp_now.h>
#include <WiFi.h>

// Example to receive data with a start marker and length byte
// For ease of testing this uses upper-case characters A and B
//       for the request and response types
//       and Z for the start marker
//    this version saves all the bytes after the start marker
//       if the TYPE byte is wrong it aborts

const byte numBytes = 32;
byte receivedBytes[numBytes];
const byte typeBytePosition = 6; // Position after the start byte
const byte requestType = 0x65;
const byte requestLength = 7;

boolean newData = false;

int LED = 21;

// REPLACE WITH THE MAC Address of your receiver
uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};

// Define variables to store Nextion readings to be sent
byte NexEventID;
byte NexPageID;
byte NexObjectID;
byte NexStatusID;

// Define variables to store incoming readings// Define variables to store incoming readings
byte incomingEventID;
byte incomingPageID;
byte incomingObjectID;
byte incomingStatusID;

// Variable to store if sending data was successful
String success;

typedef struct struct_message
{
  byte EventID;
  byte PageID;
  byte ObjectID;
  byte StatusID;
} struct_message;

// Create a struct_message called NextionInfo to hold Nextion settings
struct_message NextionInfo;

// Create a struct_message called IncomingInfo to hold incoming info
struct_message IncomingInfo;

// Callback when data is sent
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status)
{
  Serial.print("\r\nLast Packet Send Status:\t");
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
  if (status == 0)
  {
    success = "Delivery Success :)";
  }
  else
  {
    success = "Delivery Fail :(";
  }
}

// Callback when data is received
void OnDataRecv(const uint8_t *mac, const uint8_t *incomingData, int len)
{
  struct_message *IncomingInfo = (struct_message *)incomingData;
  Serial.println(WiFi.macAddress());
  // memcpy(&IncomingInfo, incomingData, sizeof(IncomingInfo));
  Serial.print("Bytes received: ");
  Serial.println(len);
  // incomingEventID = IncomingInfo.EventID;
  Serial.print((byte)IncomingInfo->EventID, HEX);
  Serial.print(' ');
  // incomingPageID = IncomingInfo.PageID;
  Serial.print((byte)IncomingInfo->PageID, HEX);
  Serial.print(' ');
  // incomingObjectID = IncomingInfo.ObjectID;
  Serial.print((byte)IncomingInfo->ObjectID, HEX);
  Serial.print(' ');
  // incomingStatusID = IncomingInfo.StatusID;
  Serial.println((byte)IncomingInfo->StatusID, HEX);
}

void emptyBuffer()
{
  for (byte n = 0; n < numBytes; n++)
  {
    receivedBytes[n] = 0;
  }
}

void recvBytesWithStartMarker()
{
  static boolean recvInProgress = false;
  static int ndx = -1;
  static byte numBytesReceived = 0;
  static byte mesgLen = 0;
  const byte startMarker = 0x65;
  byte rc;

  while (Serial2.available() > 0 && newData == false)
  {
    rc = Serial2.read();
    receivedBytes[numBytesReceived] = rc;
    numBytesReceived++;

    if (numBytesReceived > 33)
    {
      Serial.println("Error Rx : RESET   !!");
      Serial.println();
      emptyBuffer();
      numBytesReceived = 0;
      newData = false;
    }

    if (recvInProgress == true)
    {
      if (numBytesReceived == typeBytePosition)
      {
        ndx = 0; // enable saving of data (anticipate good data)
        if (rc == requestType)
        {
          mesgLen = requestLength;
        }
        else
        {
          recvInProgress = false; // abort - invalid request type
          ndx = -1;
        }
      }

      if (ndx >= 0)
      {
        ndx++;
      }

      if (numBytesReceived >= (mesgLen + typeBytePosition))
      { // got the whole message
        recvInProgress = false;
        newData = true;
      }
    }

    else if (rc == startMarker)
    {
      emptyBuffer();
      recvInProgress = true;
      numBytesReceived = 0;
      ndx = -1; // prevent counting valid bytes for the moment
    }
  }
}

// void getNexInfo()
// {
//   NexEventID = receivedBytes[0];
//   NexPageID = receivedBytes[1];
//   NexObjectID = receivedBytes[2];
//   NexStatusID = receivedBytes[3];
//   // Serial.print(NexEventID&&NexPageID&&NexObjectID&&NexStatusID);
// }

void showNewData()
{
  if (newData == true)
  {
    Serial.println(WiFi.macAddress());
    Serial.print(requestType, HEX);
    Serial.print(' ');
    for (byte n = 0; n < typeBytePosition; n++) // n < numBytes
    {
      if (n == 0)
      {
        NexEventID = receivedBytes[n];
      }
      else if (n == 1)
      {
        NexPageID = receivedBytes[n];
      }
      else if (n == 2)
      {
        NexObjectID = receivedBytes[n];
      }
      else if (n == 3)
      {
        NexStatusID = receivedBytes[n];
      }
      Serial.print(receivedBytes[n], HEX);
      Serial.print(' ');
    }
    //Serial.print(getNexInfo(),HEX);
    Serial.println();

    // Send message via ESP-NOW
    esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *)&NextionInfo, sizeof(NextionInfo));

    if (result == ESP_OK)
    {
      Serial.println("Sent with success");
    }
    else
    {
      Serial.println("Error sending the data");
    }

    newData = false;
  }
}

void sendNewData()
{
  // Set values to send
  NextionInfo.EventID = NexEventID;
  NextionInfo.PageID = NexPageID;
  NextionInfo.ObjectID = NexObjectID;
  NextionInfo.StatusID = NexStatusID;

  // Send message via ESP-NOW
  esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *)&NextionInfo, sizeof(NextionInfo));

  if (result == ESP_OK)
  {
    Serial.println("Sent with success");
  }
  else
  {
    Serial.println("Error sending the data");
  }
}

void setup()
{
  pinMode(LED, OUTPUT);
  Serial.begin(250000);
  Serial2.begin(115200);

  while (!Serial)
  {
    ;
  }

  // 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(OnDataSent);

  // Register peer
  esp_now_peer_info_t peerInfo;

  memcpy(peerInfo.peer_addr, 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;
  }

  // Register for a callback function that will be called when data is received
  esp_now_register_recv_cb(OnDataRecv);

  //Setup has completed
  Serial.println("<ESP32 is ready>");
}

void loop()
{
  recvBytesWithStartMarker();
  showNewData();
}

Most of this has come from various tutorials across the web including YouTube and RandomNerdTutorials. I am by no means a master programmer, but I am trying to learn.

Here are the results I get from the serial monitors:

ESP32 1:

�<ESP32 is ready>
AC:67:B2:36:AA:A8
65 1 2 1 FF FF FF
Sent with success

Last Packet Send Status:        Delivery Success

ESP32 2:

AC:67:B2:35:19:D8
Bytes received: 4
0 0 0 0

Note that I am only sending 4 bytes of info (65 1 2 1), so it seems to match up (I'm not sending FF FF FF)...

Thanks again for any help!!

  • You never copy out the data from the receiving buffer `incomingData` into your struct `IncomingData`because you comment out the line`// memcpy(&IncomingInfo, incomingData, sizeof(IncomingInfo));`, so you are trying to print out an entry struct... – hcheung May 13 '21 at 10:25
  • Thanks for pointing that out!! When I uncomment that line, I get this: AC:67:B2:35:19:D8 Bytes received: 4 Guru Meditation Error: Core 0 panic'ed (LoadProhibited). Exception was unhandled. Any thoughts on what is happening?? – Fireman1224 May 14 '21 at 11:21
  • Core 0 register dump: PC : 0x400d05e6 PS : 0x00060230 A0 : 0x8013052c A1 : 0x3ffb5720 A2 : 0x3ffc1770 A3 : 0x00000000 A4 : 0x00000004 A5 : 0x3ffc6014 A6 : 0x00060423 A7 : 0x00000000 A8 : 0x800d05e2 A9 : 0x3ffb5700 A10 : 0x00000003 A11 : 0x00000001 A12 : 0x00000010 A13 : 0x00000001 A14 : 0x00060023 A15 : 0x00000000 SAR : 0x00000010 EXCCAUSE: 0x0000001c EXCVADDR: 0x00000000 LBEG : 0x400014fd LEND : 0x4000150d LCOUNT : 0xffffffff ELF file SHA256: 0000000000000000 – Fireman1224 May 14 '21 at 11:23
  • Backtrace: 0x400d05e6:0x3ffb5720 0x40130529:0x3ffb5760 0x400ec505:0x3ffb5780 0x400ec3f4:0x3ffb57b0 0x400e80da:0x3ffb57d0 0x400e8279:0x3ffb5910 0x400ffb69:0x3ffb5930 0x401016e0:0x3ffb5970 0x400897ca:0x3ffb59a0 Rebooting... ⸮⸮>⸮⸮⸮ Brownout detector was triggered – Fireman1224 May 14 '21 at 11:23
  • Is there any reason you comment out the lines like ` // incomingEventID = IncomingInfo.EventID;` and change the code to `(byte)IncomingInfo->EventID`? – hcheung May 14 '21 at 12:24
  • Start with simple and testing out with the [examples](https://github.com/HarringayMakerSpace/ESP-Now) first before you are trying to add your own codes. Once question at a time, if you still have problem, post it as a new question. – hcheung May 14 '21 at 12:30
  • @hcheung - I have pulled code from multiple examples and have tried to integrate parts one at a time. I commented out the 'incomingEventID = IncomingInfo.EventID;' because I was getting an error due to the '(byte)IncomingInfo->EventID' belonging to a function from another example. I've tried making single changes using examples to adapt to what I need, up to the point I could see what I was sending (or think) but haven't been able to decode and print the correct information. I seem to only get the panic'ed result with a reboot or receive and print 0's... – Fireman1224 May 19 '21 at 18:31

1 Answers1

0

I was able to resolve my issue. Below is the code that displayed the same information that was sent from the host and received by the slave ESP32.

#include <Arduino.h>
#include <esp_now.h>
#include <WiFi.h>

// Example to receive data with a start marker and length byte
// For ease of testing this uses upper-case characters A and B
//       for the request and response types
//       and Z for the start marker
//    this version saves all the bytes after the start marker
//       if the TYPE byte is wrong it aborts

const byte numBytes = 32;
byte receivedBytes[numBytes];
const byte typeBytePosition = 6; // Position after the start byte
const byte requestType = 0x65;
const byte requestLength = 7;

boolean newData = false;

int LED = 2;

// REPLACE WITH THE MAC Address of your receiver
uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};

// Variable to store if sending data was successful
String success;

struct __attribute__((packed)) dataPacket 
{
  byte EventID;
  byte PageID;
  byte ObjectID;
  byte StatusID;
} packet, *packetPtr;



const dataPacket onLoc1R = {0x65, 0x01, 0x01, 0x01};
const dataPacket offLoc1R = {0x065, 0x01, 0x01, 0x00};
const dataPacket onLoc1L = {0x65, 0x01, 0x02, 0x01};
const dataPacket offLoc1L = {0x65, 0x01, 0x02, 0x00};

// Callback when data is sent
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status)
{
  Serial.print("\r\nLast Packet Send Status:\t");
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}

void emptyBuffer()
{
  for (byte n = 0; n < numBytes; n++)
  {
    receivedBytes[n] = 0;
  }
}

void recvBytesWithStartMarker()
{
  static boolean recvInProgress = false;
  static int ndx = -1;
  static byte numBytesReceived = 0;
  static byte mesgLen = 0;
  const byte startMarker = 0x65;
  byte rc;

  while (Serial2.available() > 0 && newData == false)
  {
    rc = Serial2.read();
    receivedBytes[numBytesReceived] = rc;
    numBytesReceived++;

    if (numBytesReceived > 33)
    {
      Serial.println("Error Rx : RESET   !!");
      Serial.println();
      emptyBuffer();
      numBytesReceived = 0;
      newData = false;
    }

    if (recvInProgress == true)
    {
      if (numBytesReceived == typeBytePosition)
      {
        ndx = 0; // enable saving of data (anticipate good data)
        if (rc == requestType)
        {
          mesgLen = requestLength;
        }
        else
        {
          recvInProgress = false; // abort - invalid request type
          ndx = -1;
        }
      }

      if (ndx >= 0)
      {
        ndx++;
      }

      if (numBytesReceived >= (mesgLen + typeBytePosition))
      { // got the whole message
        recvInProgress = false;
        newData = true;
      }
    }

    else if (rc == startMarker)
    {
      emptyBuffer();
      recvInProgress = true;
      numBytesReceived = 0;
      ndx = -1; // prevent counting valid bytes for the moment
    }
  }
}


void showNewData()
{
  if (newData == true)
  {
    Serial.println(WiFi.macAddress());
    Serial.print(requestType, HEX);
    packet.EventID = requestType;
    Serial.print(' ');
    for (byte n = 0; n < typeBytePosition; n++) // n < numBytes
    {
      if (n == 0)
      {
        packet.PageID = receivedBytes[n];
      }
      else if (n == 1)
      {
        packet.ObjectID = receivedBytes[n];
      }
      else if (n == 2)
      {
        packet.StatusID = receivedBytes[n];
      }
      Serial.print(receivedBytes[n], HEX);
      Serial.print(' ');
    }
    Serial.println();

    // Send message via ESP-NOW
    esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &packet, sizeof(packet));

    if (result == ESP_OK)
    {
      Serial.println("Sent with success");
    }
    else
    {
      Serial.println("Error sending the data");
    }

    newData = false;
  }
}

// Callback when data is received
void OnDataRecv(const uint8_t *mac, const uint8_t *data, int len)
{
  Serial.println(WiFi.macAddress());
  memcpy(&packet, data, sizeof(packet));

  Serial.printf("%x %x %x %x\n",(byte) packet.EventID,(byte) packet.PageID,(byte) packet.ObjectID,(byte) packet.StatusID);

  Serial.println();
}

void sendNewData()
{
  // Send message via ESP-NOW
  esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &packet, sizeof(packet));

  if (result == ESP_OK)
  {
    Serial.println("Sent with success");
  }
  else
  {
    Serial.println("Error sending the data");
  }
}

void setup()
{
  pinMode(LED, OUTPUT);
  Serial.begin(250000);
  Serial2.begin(115200);

  while (!Serial)
  {
    ;
  }

  // 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(OnDataSent);

  // Register peer
  esp_now_peer_info_t peerInfo;

  memcpy(peerInfo.peer_addr, 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;
  }

  // Register for a callback function that will be called when data is received
  esp_now_register_recv_cb(OnDataRecv);

  //Setup has completed
  Serial.println("<ESP32 is ready>");

}

void loop()
{
  recvBytesWithStartMarker();
  showNewData();
}