0

我是编程新手,直到现在一直在完成这个项目。我通过 ESP_NOW 与 6 个 esp32 之间发送数据,其中一个连接到 Arduino Due。正在发送的数据是一系列字节(即:65 1 1 1)。

数据源自 Nextion 显示器并通过 Serial 传输到 ESP32,然后 ESP32 使用 ESP_NOW 将该数据传输到另一个 ESP32,该 ESP32 在 Due 上连接到 Serial2。我可以在 Due 的串行监视器上打印从 Nextion 显示器传输的信息,但我似乎无法以我可以用来做某事的形式(比如转动 LED)。我在所有 ESP32 和 Due 的修改版本上使用相同的代码。

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;

struct button 
{
  byte buttonAddress[4]; //= {(byte) packet.EventID,(byte) packet.PageID,(byte) packet.ObjectID,(byte) packet.StatusID};
};

// 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};

const button onLoc1R = {0x65, 0x01, 0x01, 0x01};
const button offLoc1R = {0x065, 0x01, 0x01, 0x00};
const button onLoc1L = {0x65, 0x01, 0x02, 0x01};
const button 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);
  
  if (WiFi.macAddress() ==  "AC:67:B2:35:19:D8") // ESP32 connected to Arduino Due
  {
    // Serial2.write((byte) packet.EventID && (byte) packet.PageID && (byte) packet.ObjectID && (byte) packet.StatusID);
    Serial2.write((byte) packet.EventID);
    Serial2.write((byte) packet.PageID);
    Serial2.write((byte) packet.ObjectID);
    Serial2.write((byte) packet.StatusID);
    // digitalWrite(LED,HIGH);
    // delay(500);
    // digitalWrite(LED,LOW);
    // delay(500);
    // digitalWrite(LED,HIGH);
    // delay(500);
    // digitalWrite(LED,LOW);
  }

  // if (WiFi.macAddress() ==  "AC:67:B2:36:AA:A8")
  // {
  //   // Serial2.write((byte) packet.EventID && (byte) packet.PageID && (byte) packet.ObjectID && (byte) packet.StatusID);
  //   digitalWrite(LED,HIGH);
  //   delay(100);
  //   digitalWrite(LED,LOW);
  // }

Serial.println();



  // if (onLoc1L == format("%x %x %x %x\n",(byte) packet.EventID,(byte) packet.PageID,(byte) packet.ObjectID,(byte) packet.StatusID))
  // {

  // }
  // if (packet.EventID == 65)
  // // if (packet.EventID == ((byte) 0x65))
  // {
  //   if (packet.PageID == 1)
  //   // if (packet.PageID == ((byte) 0x01))
  //   {
  //     if (packet.StatusID == 1)
  //     // if (packet.StatusID == ((byte) 0x01))
  //     {
        // digitalWrite(LED,HIGH);
        // delay(1000);
  //     }
  //     else if (packet.StatusID == 0)
  //     // else if (packet.StatusID == ((byte) 0x00))
  //     {
        // digitalWrite(LED,LOW);
  //     }
  //   }
  // }
}

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();
}

和 Arduino Due 代码:

#include <Arduino.h>

const int BUFFER_SIZE = 3;
byte buf[BUFFER_SIZE];

int LED = 22;

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

// Attempt to create an array to group the bytes together for use in if statements
struct button
{
  byte buttonAddress[3];
};

// Definitions of variables wanted for the array if statements

button btnReceived = {packet.PageID, packet.ObjectID, packet.StatusID};

const button onLoc1R = {0x01, 0x01, 0x01};
const button offLoc1R = {0x01, 0x01, 0x00};
const button onLoc1L = {0x01, 0x02, 0x01};
const button offLoc1L = {0x01, 0x02, 0x00};


void OnDataRecv()
{
  int rxlen = Serial2.available(); // number of bytes available in Serial buffer

  if (rxlen > 0)
  {
    int rlen; // number of bytes to read

    if (rxlen > BUFFER_SIZE) // check if the data exceeds the buffer size
    {
      rlen = BUFFER_SIZE; // if yes, read BUFFER_SIZE bytes. The remaining will be read in the next time
    }
    else
    {
      rlen = rxlen;
    }
    while (rlen == BUFFER_SIZE)
    {
      // read the incoming bytes:
      rlen = Serial2.readBytes(buf, rlen);
      // rlen = Serial2.read();
      for (int i = 0; i < rlen; i++)
      {
        if (i == 0)
        {
          packet.PageID = buf[i];
        }
        else if (i == 1)
        {
          packet.ObjectID = buf[i];
        }
        else if (i == 2)
        {
          packet.StatusID = buf[i];
        }
        Serial.print(buf[i], HEX);
      }
      Serial.println();
    }
  }

  // This is the area I cant seem to work out: 

  if (btnReceived.buttonAddress == onLoc1L.buttonAddress)
  {
    digitalWrite(LED, HIGH);
    delay(100);
  }
  else
  {
    digitalWrite(LED, LOW);
  }
}

//

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

  while (!Serial)
  {
    ;
  }

  Serial.println("Arduino Due Ready");
}

void loop()
{
  OnDataRecv();
}

在此先感谢您提供有关如何完成此操作的任何帮助或建议。如果我还需要更改某些内容,请告诉我,我基本上遵循了基本示例并修改了代码行以使其工作到这一点。

4

0 回答 0