2017-09-26 40 views
0

接受數據I建立一個實驗室中的MCU來測試隨機數發生器檔。 MCU在(0,255)範圍內生成randrom,並將它們發送到PC。在PC中,我寫了一個處理pde逐行讀取並繪製爲x,y繪製隨機點。處理平局()只要通過串行端口

我的MCU打印出如下:

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

的隨機數被打印爲 「%d,%d \ r \ n」 個。到目前爲止,MCU中的RNG運行良好。

在PC處理PDE代碼,如果我用的Math.random()作爲本地RNG,它工作得很好,如果我讀每一行,並打印到控制檯,它工作得很好了。但是,如果我它們合併起來,平局()會得出一些點,然後攤.....

/* 
* 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(); 
} 

我挑選處理,因爲它是專爲互動,也許是在代碼中的錯誤,但我對此毫無頭緒。

我應該實現這兩個獨立的線程,一個用於讀取和推排隊,另一個用於繪圖?

回答

0

你只是產生無限的隨機數?如果是這樣,這是一個無限循環:

while (myPort.available() > 0) { 

我應該實現這兩個獨立的線程,一個用於讀取和推排隊,另一個用於繪圖?

可能不是。你可能只想一次讀一行。或者修改你的程序,使其不發送無限的隨機數。

+0

因爲我不知道什麼時候該發生器可以填補(256,256)的區域。所以我使用了無限循環。我將嘗試使用wxPython的,或者我會在一個較長的字節打印更多的隨機資料,如128B與\ r \ n。畢竟,時間間隔並不重要。 –