0

我是个菜鸟,刚开始使用 PlatformIO 和 Arduino/ESP32。我还想提前感谢我能得到的任何帮助。

计划:

我有 2 个 ESP32 正在通过 ESP_NOW 通话,我只是无法验证正在发送的数据以推进我的项目。基本上,我有一个 Nextion 显示器,它将特定信息发送到 ESP32(经过测试和工作),然后 ESP32 将通过 ESP_NOW 将该信息发送到另一个 ESP32,后者会将其转换为串行数据以发送到 Arduino Due 并执行一些任务。

问题:

我遇到的问题是,当我测试时,我看到我认为我正在传输的数据,但是当我尝试 Serial.print 所说的信息时,我得到“0 0 0 0”。我不确定我是否正确发送或接收数据。我所知道的是,当我按下 Nextion 上的按钮时,我会在未连接的 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 = 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();
}

其中大部分来自网络上的各种教程,包括 YouTube 和 RandomNerdTutorials。我绝不是一名高级程序员,但我正在努力学习。

以下是我从串行监视器得到的结果:

ESP32 1:

�&lt;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

请注意,我只发送 4 个字节的信息(65 1 2 1),所以它似乎匹配(我没有发送 FF FF FF)...

再次感谢任何帮助!!

4

1 回答 1

0

我能够解决我的问题。下面是显示从主机发送并由从属 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();
}
于 2021-05-13T11:57:42.440 回答