[英]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.