Serial write lag at high frequencys

Flydroid

Member
Hi,

I have an application where i am sending data from a teensy 3.1 over serial via usb to software running on the pc.
The application has a variable on how often data is send.
When sending with less than 200Hz the output is streaming fine. When i go higher with the frequency the data is coming in as chunks.
Which is bad for the continuous plotting of my data inside the software.

Here is a sample code were you can test it. Just test with different values for hz.
Code:
const byte COMMANDLENGTH = 2;
int hz = 250;
void setup()
{
  // start serial port at 9600 bps and wait for port to open:
  Serial.begin(9600);


}

void loop()
{
  unsigned char sendcommand[COMMANDLENGTH];
  for (int i=0; i < COMMANDLENGTH; i++){
        sendcommand[i] = 0x41+i;
   } 
  Serial.write(sendcommand,COMMANDLENGTH);
  Serial.print(micros());
  
  delay(1000/hz);
     
}

I know that this must be some kind of buffer problem but on the teensy or on the software (windows) side?
I did test it with arduino console, visual studio and inside my software application, no differences.
 
Perhaps you're seeing the effect of integer round-off in "delay(1000/hz)" ?

Maybe try "delayMicroseconds(1000000/hz)".

Or better yet, use elapsedMicros to wait until exactly the right amount of time as elapsed since your last transmission. That will account for the tiny amount of time your code spends composing and sending the message.
 
(Thanks Paul, delayMicroseconds does work well.
But i will look into the elapsedMicros as well. There is some optimization potential left :) )

EDIT:
Oh well, i did a nice typo fail: i tested with delayMicroseconds(10000000/hz) and well for z=500 the real Frequency would be 50Hz which does work fine.

But even with:
Code:
elapsdeMicros my_time;
if(my_time >=(1000000/hz)){
  unsigned char sendcommand[COMMANDLENGTH];
  for (int i=0; i < COMMANDLENGTH; i++){
        sendcommand[i] = 0x41+i;
   }
  Serial.write(sendcommand,COMMANDLENGTH);
  my_time=0;
  Serial.print(micros());
  }

the data is coming in chunks for hz>200.
The chunks have the size of ~700 Serial.writes.
 
Last edited:
Back
Top