Why is serial.write() laggy compared to a normal arduino?

Status
Not open for further replies.

Zane470

Member
Hello,

I'm trying to write data to the serial port at 1Khz and then I'm plotting it with SerialPlot: https://hackaday.io/project/5334-serialplot-realtime-plotting-software/discussion-88924

On a normal arduino it is smooth + works well, but on all of my teensies there is some sort of a buffering / delay effect where it appears to be writing the data to the serial port in chunks. Here is my code and an example of the code running on an arduino uno vs a teensy.

Here is the code:

Code:
void setup()
{
  Serial.begin(256000);
  delay(1000);
}

void loop()
{
  uint16_t a, b, c;

  a = random(0, 500);
  b = random(1000, 1500);
  c = random(2000, 2500);

  // Frame start byte
  Serial.write(0xAB);

  // a
  Serial.write(a & 0xff);
  Serial.write((a >> 8) & 0xff);

  // b
  Serial.write(b & 0xff);
  Serial.write((b >> 8) & 0xff);

  // c
  Serial.write(c & 0xff);
  Serial.write((c >> 8) & 0xff);

  delay(1);
}

Here is what happens when I run the code on an Uno (nice and smooth):
https://gifyu.com/image/WYFw

Here is what happens when I run the code on a Teensy (not smooth):
https://gifyu.com/image/WYCy
 
Never mind, figured it out.

Just needed to add Serial.send_now() at the end to send everything in the TX buffer -- https://www.pjrc.com/teensy/td_serial.html#txbuffer

Code:
void setup()
{
  Serial.begin(256000);
  delay(1000);
}

void loop()
{
  uint16_t a, b, c;

  a = random(0, 500);
  b = random(1000, 1500);
  c = random(2000, 2500);

  // Frame start byte
  Serial.write(0xAB);

  // a
  Serial.write(a & 0xff);
  Serial.write((a >> 8) & 0xff);

  // b
  Serial.write(b & 0xff);
  Serial.write((b >> 8) & 0xff);

  // c
  Serial.write(c & 0xff);
  Serial.write((c >> 8) & 0xff);

  Serial.send_now();

  delay(1);
}
 
Status
Not open for further replies.
Back
Top