Serial timing weird

hi!

I tried to search for an answer for this but I can’t even put it into google in a way that addresses the problem I am having, so here it goes:

On a custom board I designed based on Arduino M0 (SparkFun SAMD21 breakout actually), I am communicating via Serial (pins 30 and 31) the SAMD21 and a SAMD11.

Communication works fine, I am sending 8 bytes to the SAMD11 for it to light up neo pixels in different colours, and they light up just fine. I attach a picture for you :slight_smile:

The code that sends the packet is this:

typedef enum SerialBytes{
  msgLength = 0, nRing, ringStateH, ringStateL, R, G, B, ENDOFFRAME
};

unsigned long antMicrosSerialFor = micros();
for(int i = msgLength; i <= ENDOFFRAME; i++){
  unsigned long antMicrosSerial = micros();
  Serial.write(sendSerialBuffer[i]);
  SerialUSB.println(micros()-antMicrosSerial);
  
}
 SerialUSB.println(micros()-antMicrosSerialFor);

As you can see, it’s just a for loop that goes from 0 to 7 (8 bytes), this I checked.

I see the timing for each Serial.write inside the for loop and I get 3 microseconds. This, times 8 bytes should be 24-26 us.

Well, it’s not. If I see the timing for the whole for loop (commenting out the SerialUSB prints inside the loop), I get around 520 us.

I am developing an application in which 500 us is not desirable. Moving to another protocol like SPI is possible, but I want to understad this.

What am I missing?

Thanks!

I see the timing for each Serial.write inside the for loop and I get 3 microseconds. This, times 8 bytes should be 24-26 us.

Serial.write() just writes into a buffer and returns immediately. The actual serial transfer is made in the background. Use Serial.flush() to wait for all bytes in the buffer to be sent.

Post complete code to get timing explanations, there might be a lot of other stuff that might influence the timing in your sketch.

Hi Pylon!

Many thanks for your answer, I wasn't aware of this behaviour of the write() and flush() functions.

I finally realized that both SAMD21 and SAMD11 support much higher speeds for the serial comm, so I went up to 1.000.000 Mbaud/s and it's working like a charm.

I did not post the rest of the code, but it was a while(1) on the setup with for loops changing the values the serial sent, so nothing messing up with the timing.

I didn't post it cause this was part of a huge sketch, I was testing this part only, but you were right to point this out.

Anyway, I think I am good with your answer, thank you!