My program getting slower when I write datas on Serial Port

Hello,

Please do not duplicate post.

Related post:

I wrote some quick code to:

  • Send data from Processing to Arduino (Serial)
  • Send data received to another serial port (Serial1) to monitor incoming data on Arduino monitor (or other terminal software).

It was sending and receiving just fine.

Some observations about your code below.

Processing:

  • It is set to 80 fps.
  • Sending the same data string 5 times in a loop every frame.

Is this necessary? If not slow things down.

I will post code when I clean it up

Arduino *updated*
long w0, w1, w2, w3, w4; // speed in number step /second
boolean dataReady = false;

void setup()
  {
  Serial.begin (9600);  // From Processing
  Serial1.begin (9600); // Arduino Monitor

  Serial1.print ("A "); Serial1.println (-4);
  Serial1.print ("B "); Serial1.println (-3);
  Serial1.print ("C "); Serial1.println (-2);
  Serial1.print ("D "); Serial1.println (-1);
  Serial1.print ("E "); Serial1.println (-10);
  }

void loop()
  {
  receiveData(); // receive data from Processing
  Serial1.println ("loop"); // Mostly for debugging to see of receivData() was blocking code.
  }

void receiveData()
  {
  if (Serial.available() > 0)
    {
//    String inString = Serial.readStringUntil('*');
//    Serial1.println(inString);
//    
//    int inByte = Serial.read();
//    Serial1.print(char(inByte));

    w0 = Serial.parseInt();
    w1 = Serial.parseInt();
    w2 = Serial.parseInt();
    w3 = Serial.parseInt();
    w4 = Serial.parseInt();
    dataReady = true;
    }

  if (dataReady)
    {
    Serial1.println(w0);
    Serial1.println(w1);
    Serial1.println(w2);
    Serial1.println(w3);
    Serial1.println(w4);  
    //dataReady == false; //Arduino flagged this as an error!
    dataReady = false; // Correction
    
}
  }

  
Processing
import processing.serial.*;
Serial arduinoPort;

void setup() 
  {
  frameRate(60); 
  size(500, 500, P3D);
  
  String[] ports = Serial.list();
  printArray(Serial.list());
  arduinoPort = new Serial(this, ports[4],9600);//Carefull: chosse the port matching to the serial list  
  delay(2000); //Arduino reboots when making a serial connection; this gives it some time to be ready. 
  }

void draw() 
  {
  if(frameCount%30 == 0) //Does a write every .5 sec
    arduinoPos( );
  }

void arduinoPos () 
  {
  //for (int i = 0; i < 5; i++) //Why?
    {
    String pos = (-232) +"*"+(4232) +"*"+(1111)+"*"+(56232)+"*"+(-222)+"*"; 
    print ("  pos   ");
    println (pos);
    arduinoPort.write(pos); // Send data to Arduino.
    //arduinoPort.write('\n'); //Use if you want this to end string
    }  
  }   

:)

1 Like