Forum Rule: Always post complete source code & details to reproduce any issue!
Results 1 to 3 of 3

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

  1. #1
    Junior Member
    Join Date
    Dec 2018
    Posts
    17

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

    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-ser...scussion-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

  2. #2
    Junior Member
    Join Date
    Dec 2018
    Posts
    17
    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);
    }

  3. #3
    Senior Member+ KurtE's Avatar
    Join Date
    Jan 2014
    Posts
    7,619
    likewise you can use Serial.flush();

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •