如何在 IF 语句中使用串行数据在 Arduino Due 上做一些事情

问题描述

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

数据源自 Nextion 显示器并通过串行传输到 ESP32,然后 ESP32 使用 ESP_NOW 将该数据传输到连接到 Due 上的 Serial2 的另一个 ESP32。我能够在 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};

// 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};
// const dataPacket offLoc1R = {0x065,0x00};
// const dataPacket onLoc1L = {0x65,0x02,0x01};
// const dataPacket offLoc1L = {0x65,0x00};

const button onLoc1R = {0x65,0x01};
const button offLoc1R = {0x065,0x00};
const button onLoc1L = {0x65,0x01};
const button offLoc1L = {0x65,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.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,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.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,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};
const button offLoc1R = {0x01,0x00};
const button onLoc1L = {0x01,0x01};
const button offLoc1L = {0x01,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();
}

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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...