serialEvent() writing to serial twice when returning

Hello! I've just come across this problem today, and I have absolutely no idea what's causing it because, logically, there is no reason for it to be doing this.

void serialEvent() {
  int availableBytes = Serial.available();
  if (availableBytes) {
    Serial.readBytes(readData, availableBytes);
    DWORD theResult = *(DWORD*)readData;
    
    memset(data, 0, 32);
    DWORD* dwData = (DWORD*)data;
    dwData[0] = 2;
    dwData[1] = theResult;
    Serial.write(data, 32);
    Serial.flush();
    memset(data, 0, 32);
  }
  delay(1000);
}

In short, what my program is doing is reading some data sent from my computer and sending it back to it to print on an on-screen console. It works the first time, but for some reason, it's being sent twice with the first four bytes exactly the same. Here are the results:

[Packet 1] 0 0 0 0 1 0 0 0 7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[Packet 2] 2 0 0 0 7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[Packet 3] 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

What really matters is the third packet. In all the packets, the first four bytes describe the operation to be run on from my computer. The rest is additional data.

I've confirmed this to be the result of serialEvent() returning because, with delay(1000), the third and unwanted packet gets sent to my pc after exactly 1 second after the second packet gets sent.

Anyone got a clue on how to fix this?

your code seems to indicate a packet is 32 bytes... It is very likely that the first time you call Serial.available() it returns some number greater than 0 but less than 32.

Serial communication is incredibly slow compared to the speed of the MCU. You should be checking to make sure you have read as many chars as you are expecting before doing any processing.

Thank you! The data I was sending back to the arduino was only 4 bytes so I didn't expect there to be a delay compared to the data I was sending to the host pc, but it turned out that was the entire problem. Adding a check before reading the data on the arduino solved it.

pinkquistadotr:
Thank you! The data I was sending back to the arduino was only 4 bytes so I didn't expect there to be a delay compared to the data I was sending to the host pc, but it turned out that was the entire problem. Adding a check before reading the data on the arduino solved it.

Serial is SLOW. Divide baud rate by 10 (8 bits, plus 1 start and 1 stop bit) and that's how many characters could be sent per second maximum. This is very slow in computer time....

Thank you for the reminder! I set my baud rate to 256000, so I didn't expect to see this delay.