我需要从PC与Arduino通信。
我有C#代码。我向Arduino发送了87个字节。
C#代码
byte[] MyBuffer = new byte[87];
// I initialize buffer with bytes(0-255) details are not important.
serialport1.Write(MyBuffer, 0, 87);
Arduino部分是最重要的。因为我要将这些字节分成5个不同的数组。
byte FirstBlock[16];
byte SecondBlock[16];
byte ThirdBlock[16];
byte FourthBlock[16];
byte FifthBlock[16];
byte ReceivedBuffer[87];
int counter = 0
bool SYNC = false;
void loop(){
if(Serial.available())
CropBytes();
if(SYNC == true){
SplitBytes();
DoSomeStaffWithBlocks();
SYNC = false;
} } //End Loop
void CropBytes(){
while(Serial.available()){
byte ReceivedByte = Serial.read();
ReceivedBuffer[counter] = ReceivedByte;
// byte 35 means my byte transfer is over for ReceivedBuffer[86]
if(counter == 86 && ReceivedBuffer[counter] == 35){
SYNC = true;
counter = 0;
}
else{
counter = counter + 1;
}
}
}
void SplitBytes(){
for (int i = 5; i < 21; i++)
{
FirstBlock[i - 5] = ReceivedBuffer[i];
}
for (int i = 21; i < 37; i++)
{
SecondBlock[i - 21] = ReceivedBuffer[i];
}
for (int i = 37; i < 53; i++)
{
ThirdBlock[i - 37] = ReceivedBuffer[i];
}
for (int i = 53; i < 69; i++)
{
FourthBlock[i - 53] = ReceivedBuffer[i];
}
for (int i = 69; i < 85; i++)
{
FifthBlock[i - 69] = ReceivedBuffer[i];
}
}
问题-FirstBlock[]
,SecondBlock[]
,ThirdBlock[]
成功收到没有问题。但是在ThirdBlock
之后,FourthBlock
(第11个字节之后)和FifthBlock
(所有字节)数组不能成功初始化。
我不知道问题出在哪里。