lundi 25 septembre 2017

Processing draw() stalls as soon as accept data via serial port

I build up a lab to test random number generator in MCU. MCU generates randrom in the range of (0,255), and send them to PC. In PC, I wrote a processing pde to read line by line and draw them as x,y to draw the random points.

My MCU prints out as following:

141,188
255,198
193,224
83,138
53,68
231,142
233,232
187,210
221,204
207,86
17,240
...

The random numbers are printed as "%d,%d\r\n". So far RNG in MCU works well.

In PC processing pde code, if I use Math.random() as local RNG, it works well, if I read each line and print to console, it works well, too. However if I merge them together, the draw() will draw some points and then stalls.....

/*
 * Random_Serial_2D.pde
 */

import processing.serial.*;
import java.util.StringTokenizer;

Serial myPort;  // The serial port
String inString = null;

void setup() {
  size(256, 256);

  noSmooth();
  background(0);
  translate(0,0);

  stroke(255);

  printArray(Serial.list());
  myPort = new Serial(this, Serial.list()[0], 9600);
}

void draw() {
  int x, y;
  String[] sa = null;
  int sz;

  while (myPort.available() > 0) {
    myPort.bufferUntil('\n');
    if (inString != null){
      //print(inString);
      inString = inString.replace("\r\n","");
      sa = inString.split(",");
      sz = sa.length;

      if (sz==2){
        x = Integer.parseInt(sa[0]);
        y = Integer.parseInt(sa[1]);        
        point(x,y);      
      }
      inString = null;
    }
  }
}

void serialEvent(Serial p){
  inString = p.readString();
}

I picked Processing because it is designed for interaction, maybe there is a bug in the code, but I have no clue about it.

Should I implement it as two seperate threads, one for reading and push to queue, and the other for drawing?




Aucun commentaire:

Enregistrer un commentaire