Arduino 可变大小数组声明

Arduino Variable size Array Declaration

我在尝试 运行 以下代码时遇到错误:

int SizeOfReadArray = 10;
int PacketLength = 5;
unsigned char rmessage[SizeOfReadArray];
unsigned long flag = 0;
unsigned char DataPacket[PacketLength];
int alternate = 1;
int remaining;
int Index;

void setup() {
  // put your setup code here, to run once:
Serial.begin(115200);
}

void loop() {
  PacketExtraction();
}

void PacketExtraction(){
 // Read Serial Buffer store in array
  Serial.readBytes(rmessage,SizeOfReadArray);
  // onetime execution for getting exact message from serial buffer
  if (flag == 0){
    for (int j=0;j<SizeOfReadArray;j++){
      // check for start of packets through header bytes
      if (rmessage[j+0] == 65 && rmessage[j+1] == 65){
        // store the Index for extracting packet from message array
        Index = j;
        remaining = SizeOfReadArray-Index+PacketLength;
        flag = 1;
      }
    }
  }
  // actual packet extraction
  /* take PacketLength of data from serial burffr and store the rest
  for remaining bytes for next data packet construction */
  if (alternate == 1){
    for (int k=0;k<5;k++){
      DataPacket[k]=rmessage[k+Index];
    }
    // storing remaining bytes form next execution
    unsigned char previouspacket[remaining];
    for (int k=0;k<remaining;k++){
      previouspacket[k] = rmessage[k+Index+PacketLength];
    }
    alternate = 0;
  }
  /* now this time take the previously saved remaining bytes of packet
  and merge them with the current packet data */
  else{
    for (int k=0;k<remaining;k++){
      DataPacket[k] = previouspacket[k];
    }
    for (int k=0;k<(remaining+1);k++){
      DataPacket[k+remaining] = rmessage[k];
    }
   alternate = 1;
  }
}

错误信息:

Arduino: 1.6.1 (Windows 7), Board: "Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)"

sketch_apr04b.ino: In function 'void PacketExtraction()':

sketch_apr04b.ino:52:23: error: 'previouspacket' was not declared in this scope

Error compiling.

This report would have more information with "Show verbose output during compilation" enabled in File > Preferences.

previouspacket 仅在 if...then 块的第一个分支中声明。

您应该将 unsigned char previouspacket[remaining]; 移到 if 语句之前