[英]Processing blocks drawing function while writing to the serial port
在處理中,我編寫了一個簡單的程序,該程序獲取圖像的所有像素並將其值發送到串行端口。 這是在draw函數內部完成的,並在每個draw事件中遍歷像素數組。
因此,對於200 x 200的圖像,有40000像素,並且繪制函數被調用40000次。 但是我看不到我在此處理過程中進行任何更改的結果。 30秒后,數據將被序列化,然后所有更改才可見。
為了在串行寫入過程中立即繪制並查看結果,我需要什么? 異步線程可以解決嗎? 我也嘗試過此方法,並調用redraw方法,但似乎無濟於事。
對於200x200的圖像,您將循環遍歷40000像素,但是您不必經常調用draw()函數。 您可以為每個像素(每個draw()調用一次)運行一個循環,以防您的像素實際發生變化,否則,可以在setup()
中將像素值緩存一次
關於串行寫入,應該不會太復雜。 這是一個概念證明草圖,說明了編寫並行寫入串行的Thread的一種方法:
import processing.serial.*;
int w = 200;
int h = 200;
int np = w*h;//total number of pixels
PImage image;
SerialThread serial;
void setup(){
image = createImage(w,h,ALPHA);
//draw a test pattern
for(int i = 0 ; i < np; i++) image.pixels[i] = color(tan(i) * 127);
//setup serial
serial = new SerialThread(this,Serial.list()[0],115200);
}
void draw(){
image(image,0,0);
}
void mousePressed(){
println("writing pixel data to serial port");
for(int i = 0 ; i < np; i++) serial.write((int)brightness(image.pixels[i]));
}
//implement runnable - can run as thread, alternatively extend Thread
class SerialThread implements Runnable{
Serial serial;
boolean running = false;//keep the tread running
int data;//store a byte to send
boolean hasData;//keep track if the most recent data was written
SerialThread(PApplet parent,String port,int baudrate){
try{
//setup serial
this.serial = new Serial(parent,port,baudrate);
//setup thread
running = true;
new Thread(this).start();
}catch(Exception e){
System.err.println("error opening serial port! please check settings (port/baudrate) and the usb cable");
e.printStackTrace();
}
}
//handled
public void run(){
while(running){//endless loop to keep the thread running
if(hasData){//if there is data to write
if(serial != null) serial.write(data); //send it via serial, if the port is open
hasData = false;//mark that the data was sent
}
}
}
public void write(int data){
this.data = data;
hasData = true;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.