Arduino可变大小的阵列声明

时间:2015-04-04 21:51:02

标签: c variables compiler-errors arduino

尝试运行以下代码时出错:

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),主板:&#34; Arduino Mega或Mega 2560,   ATmega2560(Mega 2560)&#34;

     

sketch_apr04b.ino:在函数&#39; void PacketExtraction()&#39;:

     

sketch_apr04b.ino:52:23:错误:&#39; previouspacket&#39;未被宣布   这个范围

     

编译错误。

     

此报告将提供更多信息&#34;显示详细输出   在编译期间&#34;在文件&gt;中启用偏好。

1 个答案:

答案 0 :(得分:0)

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

您应该在unsigned char previouspacket[remaining];声明

之前移动if